动态路由 --- vue
动态路由:让多个组件使用同一个挂载点,并根据需求动态切换.
基础语法:
<div id="example"> <button @click="change">切换页面</button> <component :is="currentView"></component> </div>
<script>
var page1= {template:'<div>我是页面1</div>'};
var page2 = {template:'<div>我是页面2</div>'};
var page3 = {template:'<div>我是页面3</div>'};
new Vue({
el: '#example',
components: {
page1,
page2,
page3
},
data:{
index:0,
arr:['home','post','archive'],
},
computed:{
currentView(){
return this.arr[this.index];
}
},
methods:{
change(){
this.index = (++this.index)%3;
}
}
})
</script>
//如上可以动态的展示page1,2,3 但是同一挂载点同时只能展示一个组件;
keep-alive
<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
多个组件挂载时,根据条件,使只有一个组件被渲染;
<div id="example">
<button @click="change">切换页面</button>
<keep-alive>
<page1 v-if="index===0"></page1>
<page2 v-else-if="index===1"></page2>
<page3 v-else></page3>
</keep-alive>
</div>
activated 和 deactivated
activated和deactivated在<keep-alive>树内的所有嵌套组件中触发;组件被加载和卸载的时候触发点勾子;
<div id="example">
<button @click="change">切换页面</button>
<keep-alive>
<component :is="currentView" @pass-data="getData"></component>
</keep-alive>
<p>{{msg}}</p>
</div>
include 和 exclude
允许有条件的缓存,二者都可以用逗号分隔字符串、正则表达式或一个数组来表示
<keep-alive include="page1,page2">
<component :is="currentView"></component>
</keep-alive>
上面的代码,表示只缓存page1和page2,不缓存page3

浙公网安备 33010602011771号