组件

一,组件的创建

全局组件

方法一

  /*
        创建组件方式一
        先创建组件构造器,再由组件构造器创建组件
     */
    // 根据Vue.extend创建组件构造器
  var myComponent = Vue.extend({
        template:'

{{name}}

', data:function(){//组件的数据存储使用的是一个函数,用return 返回数据,全局组件不能使用vue实例的data数据(vue实际也是一个组件) return { name:"乔巴" } } }); // 再由Vue.component(标签名,组件构造器)创建组件 Vue.component('hello',myComponent); // 再由Vue.component(标签名,组件构造器)创建组件 Vue.component('hello',myComponent);

方法二(推荐)

  /*
    方法二
     */
    Vue.component('world',{
        template:'

world

' });

局部组件

     components:{
            'my-temp':{
                template:'

{{name}}

', data:function(){//子组件不能调用付组件的data数据 return { name:'娜美' } } } },

var vm = new Vue({})//vue的实例对象其他是一个组件,在vue实例里面的组件也不能那个调用vue中的data(子组件不能调用父组件的data数据)

二,template模板

let vm=new Vue({
    el:'#myApp',
    data:{ 
    },
    components:{
        'hello':{
            template:'#myTemplate',//模板的引用使用id来获取
            data:function(){
                return {
                    msg:'hello world',
                    arr:['jakc','alice','lufei'],
                    }
                }
            }
    
        },
        methods:{ 
                    
        }
    });

 
    
使用模板注意事项: 1.模板写在vue实例挂在的元素外面(#myApp),否则会报错 2.模板template标签下只能有一个根原生(vue2.必须有根原生) 3.创建组件的时候,template的值通过