详解vue父子模版嵌套案例

这里是父子模版的调用

这里是针对于vue1.0,如果要学2.0,建议大家去看官方文档

vue2.0 :

vue-router2.0: https://router.vuejs.org/zh-cn/essentials/getting-started.html

第一种,子组件模版直接写在js里

//定义模版挂载点my-component <div> <com-ponent></com-ponent> </div> <script src="https://www.jb51.net/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中定义,系统会自动调用extend函数。 var conp = new Vue({// 创建根实例 el: '#exampleBox1' }); </script>

第二种,使用HTML模版

<!-- 父组件模板 --> <div> <div>{{parent.name}}</div> <!--模版挂载标识--> <children></children> </div> <!-- 子组件模板 --> <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内部,否则找不到挂件 --> <my-component></my-component> <!-- 模版可以重用多次 ···· 只不过一样的东西没有这个必要 --> <child></child>复用一次 <child></child>复用二次 <child></child> ··· <child></child> ··· </div> <!--比如放在这里是找不到的--> <child></child> <script src="https://www.jb51.net/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); // 创建根实例,所有组件都需要在根实例之前创建。 new Vue({ el: '#example' }) </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzwfw.html