toggle效果
<head>
<meta charset="utf-8" />
<title>动态组件与v-once指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<child-one v-if='type==="child-one"'></child-one>
<child-two v-if='type==="child-two"'> </child-two>
<button @click="handleBtnClick">change</button>
</div>
<script>
Vue.component('child-one', {
template: '<div>child-one</div>'
})
Vue.component('child-two', {
template: '<div>child-two</div>'
})
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleBtnClick: function () {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
</body>
</html>
【动态组件】
<head>
<meta charset="utf-8" />
<title>动态组件与v-once指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<!--<child-one v-if='type==="child-one"'></child-one>
<child-two v-if='type==="child-two"'> </child-two>-->
<component :is="type"></component>
<button @click="handleBtnClick">change</button>
</div>
<script>
Vue.component('child-one', {
template: '<div>child-one</div>'
})
Vue.component('child-two', {
template: '<div>child-two</div>'
})
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleBtnClick: function () {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
</body>
</html>
![](https://img.haomeiwen.com/i6003554/cf7a15eb14d1508b.png)
![](https://img.haomeiwen.com/i6003554/ce7eefc6eaf80c3a.png)
【v-once指令】在模板中添加v-once指令,可以直接将模板放在内存中,而不去销毁,用的时候直接提出来,相比不断销毁再去创建,提高了性能
<head>
<meta charset="utf-8" />
<title>动态组件与v-once指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<!--<child-one v-if='type==="child-one"'></child-one>
<child-two v-if='type==="child-two"'> </child-two>-->
<component :is="type"></component>
<button @click="handleBtnClick">change</button>
</div>
<script>
Vue.component('child-one', {
template: '<div v-once>child-one</div>'
})
Vue.component('child-two', {
template: '<div v-once>child-two</div>'
})
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleBtnClick: function () {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
</body>
</html>
网友评论