在Vue中使用 JSX

前言
前排警告,这不是玩具!

那、还能是啥呢

起因
最近看到好多在Vue中使用JSX的文章,作为目前最受欢迎的MVVM框架,其实不学习还是有些对不住自己的。但是无奈太喜欢React,所以在Vue中能使用JSX还是能勾起很多人的好奇心的。

我就是,还有么

简单Demo
对于vue-cli3和4创建的Vue工程,是可以直接使用JSX语法的,简单的就是template删除了,写个render,其他的就和写React类组件差不多了。

吗😢?

还是没那么简单的,不过可以先看个简单的传值:

<script>
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "home",
  render() {
    return <HelloWorld msg="this is helloworld" />;
  }
};
</script>
<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  render() {
    return <div>{this.msg}</div>;
  }
};
</script>

<style scoped lang="less">
div {
  margin: 40px;
}
</style>

关于JSX

如果上面的示例对你没什么难度,以React的角度来说。那么我们就来看一下加上Vue的角度的一些基本的东西:

<script>
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "home",
  data() {
    return {
      data: [12, 34, 56]
    };
  },
  methods: {
    handleClick() {
      console.log(123);
    }
  },
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>click</button>
        <HelloWorld msg="this is helloworld" />
        <ul>
          {this.data.map(i => (
            <li key={i}>{i}</li>
          ))}
        </ul>
      </div>
    );
  }
};
</script>

传事件

<HelloWorld msg="this is helloworld" handleClick={this.handleClick} />

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
    handleClick: Function
  },
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>click</button>
        <div>{this.msg}</div>
      </div>
    );
  }
};
</script>
 

因为不会有React处理事件时解析语法this指向取消的问题,所以这里也不需要bind。

生命周期

Vue的生命周期很条理:

beforeCreate, created
beforeMount, mounted
beforeUpdate, updated
beforeDestroy, destroyed
这部分和JSX关系不大,

Vue-Router
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>

App.vue同样可以做这样的修改,使得我们以JSX的方式引入路由。

同时我们也可以混用template和JSX。

总结
只是简单的Demo,已经可以在迁移量不大的情况下做出一些东西了,后续会结合Vuex和Vue-router写点东西熟悉一下。

 


————————————————
版权声明:本文为CSDN博主「eswang」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43870742/java/article/details/104255946

posted @ 2020-04-08 14:26  奔跑的太阳花  阅读(2428)  评论(0编辑  收藏  举报