您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關vue中怎么實現父子模版嵌套,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
第一種,子組件模版直接寫在js里
//定義模版掛載點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);// 注冊 //注意,extend(json) 和 vue.component('com-ponent', json)//這兩個JSON是相等的。 //所以下面第二種會將extend()函數省略掉,直接在component中定義,系統(tǒng)會自動調用extend函數。 var conp = new Vue({// 創(chuàng)建根實例 el: '#exampleBox1' }); </script>
第二種,使用HTML模版
<!-- 父組件模板 --> <div id="exampleBox2" > <div>{{parent.name}}</div> <!--模版掛載標識--> <children></children> </div> <!-- 子組件模板 --> <template id="child-template"> <p >{{text}}</p> </template> <script> Vue.component('children', {//child是模版掛載的標簽名 template: '#child-template',//id對應子組件的ID data: function () { return { text: '這里是子組件的內容' } } }); var parent = new Vue({// 初始化父組件 el: '#exampleBox2', data: { parent: { name:'這里是父組件的內容' } } }) </script>
第三種、來一個復雜的
<div id="example"> <!-- 所有的模板掛件,都必須在根實例ID內部,否則找不到掛件 --> <my-component></my-component> <!-- 模版可以重用多次 ···· 只不過一樣的東西沒有這個必要 --> <child></child>復用一次 <child></child>復用二次 <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 >Parent<child-component></child-component>父模版內部</div>', components: { // 調用子組件 'child-component': Child } }); // 注冊父組件 Vue.component('my-component', Parent); //復用子組件。 Vue.component('child', Child); // 創(chuàng)建根實例,所有組件都需要在根實例之前創(chuàng)建。 new Vue({ el: '#example' }) </script>
關于vue中怎么實現父子模版嵌套就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。