详解从react转职到vue开发的项目准备

2020-06-14 06:12:30易采站长站整理

特性对比

针对视图的开发,Vue推崇html、js、css分离的写法,React推崇all-in-js,所有都在js中进行写法。

当然各有各的好处,如Vue将其进行分离,代码易读性较好,但是在html中无法完美的展示JavaScript的编程能力,而对于React的jsx写法,因为有JavaScript的编程语法支持,让我们更灵活的完成视图开发。

对于这类不灵活的情况,Vue也对jsx进行了支持,只需要在babel中添加插件

babel-plugin-transform-vue-jsx
babel-plugin-syntax-jsx
babel-helper-vue-jsx-merge-props
(babel6,对于babel7,官方推荐的
@vue/app
预设中已包含了jsx的转化插件),我们就可以像React一样,在组件中声明render函数并返回jsx对象,如下我们对上一节的组件进行改造:

组件改造


<script>
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';

@Component
export default class Demo extends Vue {

title = 'hello world';

@Prop({type: String, default: 'Vue Demo'}) title;

@Watch('title')
titleChange(newTitle, oldTitle) {
console.log(`标题从 ${oldTile} 变为了 ${newTitle}`)
}

setText(e) {
this.text = '点击了按钮';
}

render() {
const { title, text } = this;
return <div>
<h1>{title}</h1>
<span>{text}<span>
<button onClick={this.setText}>按钮<button>
</div>
}
}
</script>

Vue的jsx使用注意点

写到这里,也基本上发现其写法已经与React的class写法雷同了。那么Vue的jsx和React的jsx有什么不同呢。

在React的jsx语法需要React支持,也就是说,在你使用jsx的模块中,必须引进React。

而Vue的jsx语法需要Vue的createElement支持,也就是说在你的jsx语法的作用域当中,必须存在变量h,变量h为

createElement
的别名,这是Vue生态系统中的一个通用惯例,在render中h变量由编译器自动注入到作用域中,自动注入详情见plugin-transform-vue-jsx,如果没有变量h,需要从组件中获取并声明,


const h = this.$createElement;

这里借助官方的一个例子,基本包含了所有Vue的jsx常用语法,如下:


// ...
render (h) {
return (
<div
// normal attributes or component props.
id="foo"
// DOM properties are prefixed with `domProps`
domPropsInnerHTML="bar"
// event listeners are prefixed with `on` or `nativeOn`