vue父子模版嵌套案例

作者: ____雨歇微凉 | 来源:发表于2016-06-24 21:22 被阅读14693次

这里是父子模版的调用

这里是针对于vue1.0,如果要学2.0,建议大家去看官方文档
vue2.0 http://vuefe.cn/guide/
vue-router2.0https://router.vuejs.org/zh-cn/essentials/getting-started.html

下一篇介绍webpack与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中定义,系统会自动调用extend函数。
    var conp = new Vue({// 创建根实例
        el: '#exampleBox1' 
     });
</script>

第二种,使用HTML模版

<!-- 父组件模板 -->
<div id="exampleBox2"  style="border:1px solid #ccc;width:500px;">
    <div>{{parent.name}}</div>
    <!--模版挂载标识-->
    <children></children>
</div>
<!-- 子组件模板 -->
<template id="child-template"> 
    <p style="background:#eee;">{{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 style="border: 1px solid #ccc;width:200px;">Parent<child-component></child-component>父模版内部</div>', 
         components: {
              // 调用子组件 
             'child-component': Child 
         } 
   }); 
   // 注册父组件 
   Vue.component('my-component', Parent);
    //复用子组件。
    Vue.component('child', Child); 
   // 创建根实例,所有组件都需要在根实例之前创建。
    new Vue({ 
       el: '#example' 
   })
</script>

相关文章

网友评论

    本文标题:vue父子模版嵌套案例

    本文链接:https://www.haomeiwen.com/subject/jsaodttx.html