Vue引用模板和动态组件
2019-07-28 本文已影响0人
念念碎平安夜
一、引用模板
将组件内容放到模板<template>中并引用
<div id="itany">
<my-hello></my-hello>
<my-hello></my-hello>
</div>
//模板内容
<template id="wbs">
<!-- <template>必须有且只有一个根元素 -->
<div>
<h3>{{msg}}</h3>
<ul>
<li v-for="value in arr">{{value}}</li>
</ul>
</div>
</template>
<script>
var vm = new Vue({
el: '#itany',
components: {
'my-hello': {
name: 'wbs17022', //指定组件的名称,默认为标签名,可以不设置
template: '#wbs',
data() {
return {
msg: 'zhang',
arr: ['tom', 'jack', 'mike']
}
}
}
}
});
</script>
二、动态组件
<component :is="">组件
多个组件使用同一个挂载点,然后动态的在它们之间切换
<keep-alive>组件
<div id="itany">
<button @click="flag='my-hello'">显示hello组件</button>
<button @click="flag='my-world'">显示world组件</button>
<div>
<!-- 使用keep-alive组件缓存非活动组件,可以保留状态,避免重新渲染,默认每次都会销毁非活动组件并重新创建 -->
<keep-alive>
<component :is="flag"></component>
</keep-alive>
</div>
</div>
<script>
var vm = new Vue({
el: '#itany',
data: {
flag: 'my-hello'
},
components: {
'my-hello': {
template: '<h3>我是hello组件:{{x}}</h3>',
data() {
return {
x: Math.random()
}
}
},
'my-world': {
template: '<h3>我是world组件:{{y}}</h3>',
data() {
return {
y: Math.random()
}
}
}
}
});
</script>