首先需要知道,在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
}
})