首先是class语法支持,针对babel6及更低的版本,需要配置babel的plugin中添加class语法支持插件
babel-plugin-transform-class-properties,针对babel7,需要使用插件
@babel/plugin-proposal-class-properties对class进行语法转换。然后是装饰器语法支持,针对babel6及更低的版本,需要配置babel的plugin中添加装饰器语法支持插件
babel-plugin-transform-decorators-legacy,针对babel7,需要使用插件
@babel/plugin-proposal-decorators对装饰器进行语法转换。针对bable6,配置.babelrc如下
{
"presets": ["env", "stage-1"],
"plugins": [
"transform-runtime",
"syntax-dynamic-import",
"transform-class-properties", // 新增class语法支持
"transform-decorators-legacy" // 新增装饰器语法支持
]}
对于bable7,官方推荐直接使用
@vue/apppreset,该预设包含了
@babel/plugin-proposal-class-properties和
@babel/plugin-proposal-decorators两个插件,另外还包含了动态分割加载chunks支持
@babel/plugin-syntax-dynamic-import,同时也包含了
@babel/envpreset,.babelrc配置如下:
{
"presets": [
["@vue/app", {
"loose": true,
"decoratorsLegacy": true
}] ]}重写组件
编译插件准备好之后,我们对上面的Vue组件进行改写,代码如下
<template>
<div>
<h1>{{title}}</h1>
<span>{{text}}<span>
<button @click="setText">按钮</button>
</div>
</template><script>
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
@Component
export default class Demo extends Vue {
text = 'hello world';
@Prop({type: String, default: 'Vue Demo'}) title;
@Watch('title')
titleChange(newTitle, oldTitle) {
console.log(`标题从 ${oldTile} 变为了 ${newTitle}`)
}
setText(e) {
this.text = '点击了按钮';
}
}
</script>
到此为止,我们的组件改写完毕,相对先前的“写配置”的写法,看起来相对来说要好理解一些吧。
注意:Vue的class的写法的methods还是没办法使用箭头函数进行的,详细原因这里就不展开,大概就是因为Vue内部挂载函数的方式的原因。
视图开发










