Vue creatElement
1、传统template写法
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="app" v-cloak>
<ele></ele>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
Vue.component('ele', {
template: `
<div id="element" :class="{show:show}" @click="handleClick">
文本内容
</div>
`,
data: function() {
return {
show: true
}
},
methods: {
handleClick: function() {
console.log("clicked")
}
}
})
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>
2、Render写法
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>Vue</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<div id="app" v-cloak>
<ele></ele>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script type="text/javascript">
Vue.component('ele', {
render: function(createElement) {
return createElement(
'div', {
//动态绑定class,同:class
class: {
'show': this.show
},
//普通html特性
attrs: {
id: 'element'
},
//给div绑定click事件
on: {
click: this.handleClick
}
},
'文本内容'
)
},
data: function() {
return {
show: true
}
},
methods: {
handleClick: function() {
console.log("clicked")
}
}
});
var app = new Vue({
el: '#app'
})
</script>
</body>
</html>
区别:templat的写法可读性强,简洁。所以需要在合适的场景使用Render函数,否则会增加负担。
作者:孟繁贵 Email:meng010387@126.com 期待共同进步!