首先需要知道,在Vue根实例下,template
中的内容会自动嵌入到 el
挂载的HTML块中。
//即本来是这样:
<div id="app">
<h2>{{message}}</h2>
</div>
new Vue({
el:'#app',
data:{
message:'Hello,VueJs!'
}
})
//可以修改成这样:
<div id="app">
</div>
new Vue({
el:'#app',
template:`<h2>{{message}}</h2>`,
data:{
message:'Hello,VueJs!'
}
})
利用组件化的思想
,我们把template的内容单独写一个组件出来:
//main.js
const cpn = {
template:`<h2>{{message}}</h2>`,
data(){
return{
message:'Hello,VueJs!'
}
}
}
new Vue({
el:'#app',
template:'<cpn/>',
components:{
cpn
}
})
这样子代码还是复杂,利用组件化的思想
,我们把组件中的内容单独写在一个js文件中:
//cpn.js
export default {
template:`
<div>
<h2>{{message}}</h2>
</div>
`,
data(){
return {
message:'Hello!'
}
}
}
//main.js
import cpn from '../vue/cpn.js'
new Vue({
el:'#app',
template:'<cpn/>',
components:{
cpn
}
})
组件和根实例被分离的差不多了,接下来还有一个问题,cpn.js并没有做到模板与js代码之间的分离,接下来创建一个vue component文件,该文件默认的格式为模板、js、css的三层分离写法:
//cpn.vue
<template>
<div>
<h2 class="title">{{message}}</h2>
</div>
</template>
<script>
export default {
name:"cpn",
data(){
return {
message:'Hello!'
}
}
}
</script>
<style>
.title{
color: yellow;
}
</style>
//main.js
import cpn from '../vue/cpn.vue'
new Vue({
el:'#app',
template:'<cpn/>',
components:{
cpn
}
})