一,组件的创建
全局组件
方法一
/*
创建组件方式一
先创建组件构造器,再由组件构造器创建组件
*/
// 根据Vue.extend创建组件构造器
var myComponent = Vue.extend({
template:'<h3>{{name}}</h3>',
data:function(){//组件的数据存储使用的是一个函数,用return 返回数据,全局组件不能使用vue实例的data数据(vue实际也是一个组件)
return {
name:"乔巴"
}
}
});
// 再由Vue.component(标签名,组件构造器)创建组件
Vue.component('hello',myComponent);
// 再由Vue.component(标签名,组件构造器)创建组件
Vue.component('hello',myComponent);
方法二(推荐)
/*
方法二
*/
Vue.component('world',{
template:'<h1>world</h1>'
});
局部组件
components:{
'my-temp':{
template:'<h1>{{name}}</h1>',
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:{
}
});
<body>
<div id="myApp">
<hello></hello>
</div>
<template id="myTemplate">
<!-- template下只能有一个根元素 -->
<div>
<ul>
<li v-for="(v,k) in arr">{{v}}</li>
</ul>
</div>
</template>
</body>
使用模板注意事项:
1.模板写在vue实例挂在的元素外面(#myApp),否则会报错
2.模板template标签下只能有一个根原生(vue2.必须有根原生)
3.创建组件的时候,template的值通过 <template>的id来获取
三,动态模板
<div id="myApp">
<button @click="flag='my-hello'">显示hello</button>
<button @click="flag='my-world'">显示world</button>
<!-- 使用keep-alive组件缓存非活动组件,可以保留状态,避免重新渲染,默认每次都会销毁重新创建 -->
<keep-alive>
<!-- 多个组件使用同一个挂载点,然后动态地在他们之间切换,flag的值,决定显示哪一个组件 -->
<component :is="flag"></component>
</keep-alive>
</div>
<template id="mytemplate">
<ul>
<p>{{x}}</p>
<li v-for="value in arr">{{value}}</li>
</ul>
</template>
let vm=new Vue({
el:'#myApp',
data:{
flag:"my-hello",//flag的值决定显示的是哪个组件
},
components:{
'my-hello':{
template:'<h1>我是hello组件{{x}}</h1>',//模板的引用使用id来获取
data:function(){
return {
x:Math.random()
}
}
},
});
