本文介紹了vue父子組件的嵌套的示例代碼,分享給大家,具體如下:
組件的注冊:
先創建一個構造器
var myComponent = Vue.extend({ template: '...'})用Vue.component注冊,將構造器用作組件(例為全局組件)
Vue.component('my-component' , myComponent)注冊局部組件:
var Child = Vue.extend({ /* ... */ })var Parent = Vue.extend({ template: '...', components: { // <my-component> 只能用在父組件模板內 'my-component': Child }})注冊語法糖,簡化過程
// 在一個步驟中擴展與注冊Vue.component('my-component', { template: '<div>A custom component!</div>'})// 局部注冊也可以這么做var Parent = Vue.extend({ components: { 'my-component': { template: '<div>A custom component!</div>' } }})父子組件嵌套的例子:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>index</title></head><body><div id="app"> <parent></parent></div><script src="vue.js"></script><script> var childComponent = Vue.extend({ template: '<p>this is child template</p>' }); Vue.component("parent",{ template: '<p>this is parent template</p><child></child><child></child>', components: { 'child': childComponent, } }); var app = new Vue({ el: '#app' });</script></body></html>其與以下寫法等價:
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>index</title></head><body><template id="child"> <p>this is child template</p></template><template id="parent"> <p>this is parent template</p> <child></child> <child></child></template><div id="app"> <parent></parent></div><script src="vue.js"></script><script> var childComponent = Vue.extend({ template: '#child' }); Vue.component("parent",{ template: '#parent', components: { 'child': childComponent, } }); var app = new Vue({ el: '#app' });</script></body></html>頁面顯示:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答