用Vue 2.0中的render函数实现
script.js
new Vue({
el: '#app',
data: {
msg: 'Click to see the message'
},
methods: {
hello () {
alert('This is the message')
}
},
render (createElement) {
return createElement(
'span',
{
class: { 'my-class': true },
style: { cursor: 'pointer' },
on: {
click: this.hello
}
},
[ this.msg ]
);
},
});
index.html
<div id="app"><!--span will render here--></div>
使用JSX来实现
script.js
new Vue({
el: '#app',
data: {
msg: 'Click to see the message.'
},
methods: {
hello () {
alert('This is the message.')
}
},
render: function render(h) {
return (
<span
class={{ 'my-class': true }}
style={{ cursor: 'pointer' }}
on-click={ this.hello }
>
{ this.msg }
</span>
)
}
});
index.html和上文一样。
babel-plugin-transform-vue-jsx
正如前文所说, JSX是需要编译为JavaScript才可以运行的, 所以第三个样例需要有额外的编译步骤。这里我们用Babel和Webpack来进行编译。
打开你的webpack.config.js文件, 加入babel loader:
loaders: [
{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }
]
新建或者修改你的.babelrc文件,加入 babel-plugin-transform-vue-jsx 这个插件
{
"presets": ["es2015"],
"plugins": ["transform-vue-jsx"]
}
现在运行webpack, 代码里面的JSX就会被正确的编译为标准的JavaScript代码。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
