這里是父子模版的調(diào)用
這里是針對(duì)于vue1.0,如果要學(xué)2.0,建議大家去看官方文檔
vue2.0 http://vuefe.cn/guide/
vue-router2.0https://router.vuejs.org/zh-cn/essentials/getting-started.html
下一篇介紹webpack與vue配合,組件總不能都寫(xiě)在一個(gè)文件里吧。
第一種,子組件模版直接寫(xiě)在js里
//定義模版掛載點(diǎn)my-component
<div id="exampleBox1">
<com-ponent></com-ponent>
</div>
<script src="../vue/node_modules/vue/dist/vue.js"></script>
<script>
var Component = Vue.extend({// 定義
template: '<div>A custom component!</div>',
data: function () {
return {
name: 'yuxie'
}
}
});
Vue.component('com-ponent', Component);// 注冊(cè)
//注意,extend(json) 和 vue.component('com-ponent', json)//這兩個(gè)JSON是相等的。
//所以下面第二種會(huì)將extend()函數(shù)省略掉,直接在component中定義,系統(tǒng)會(huì)自動(dòng)調(diào)用extend函數(shù)。
var conp = new Vue({// 創(chuàng)建根實(shí)例
el: '#exampleBox1'
});
</script>
第二種,使用HTML模版
<!-- 父組件模板 -->
<div id="exampleBox2" style="border:1px solid #ccc;width:500px;">
<div>{{parent.name}}</div>
<!--模版掛載標(biāo)識(shí)-->
<children></children>
</div>
<!-- 子組件模板 -->
<template id="child-template">
<p style="background:#eee;">{{text}}</p>
</template>
<script>
Vue.component('children', {//child是模版掛載的標(biāo)簽名
template: '#child-template',//id對(duì)應(yīng)子組件的ID
data: function () {
return {
text: '這里是子組件的內(nèi)容'
}
}
});
var parent = new Vue({// 初始化父組件
el: '#exampleBox2',
data: {
parent: {
name:'這里是父組件的內(nèi)容'
}
}
})
</script>
第三種、來(lái)一個(gè)復(fù)雜的
<div id="example">
<!-- 所有的模板掛件,都必須在根實(shí)例ID內(nèi)部,否則找不到掛件 -->
<my-component></my-component>
<!-- 模版可以重用多次 ···· 只不過(guò)一樣的東西沒(méi)有這個(gè)必要 -->
<child></child>復(fù)用一次
<child></child>復(fù)用二次
<child></child> ···
<child></child> ···
</div>
<!--比如放在這里是找不到的-->
<child></child>
<script src="../vue/node_modules/vue/dist/vue.js"></script>
<script>
//定義子組件,子組件必須在父組件之前定義。
var Child = Vue.extend({template: '<div>A child component!</div>'});
//定義父組件
var Parent = Vue.extend({
template: '<div style="border: 1px solid #ccc;width:200px;">Parent<child-component></child-component>父模版內(nèi)部</div>',
components: {
// 調(diào)用子組件
'child-component': Child
}
});
// 注冊(cè)父組件
Vue.component('my-component', Parent);
//復(fù)用子組件。
Vue.component('child', Child);
// 創(chuàng)建根實(shí)例,所有組件都需要在根實(shí)例之前創(chuàng)建。
new Vue({
el: '#example'
})
</script>