首页 > 其他分享 >Vue keep-alive缓存路由信息

Vue keep-alive缓存路由信息

时间:2023-02-14 15:38:32浏览次数:44  
标签:Vue console log Two alive keep let


在不使用keep-alive时,通过路由跳转到另一组件上时,上一个组件会被vue销毁,在次进入,页面会保持初始状态,不会对用户的更改保留,如果需要包作在某组件上的更改,就可以使用keep-alive保存路由入口

<keep-alive>
<router-view></router-view>
</keep-alive>
<body>
<div id="app"></div>
<script>
let One = {
template: `<div>
<h1 @click="changeColor">One</h1>
</div>`,
methods: {
changeColor(e) {
e.target.style.color = 'green';
}
},
created() {
console.log("One-created");
},
mounted() {
console.log("One-mounted");
},
destroyed() {
console.log('One-destroyed');
//使用了keep-alive 组件不再销毁,所以这条不会打印,不用keep-alive会显示这条调试,也就是说使用keep-alive组件缓存了不会销毁,这种实现视需求而定,是否要再返回某一页面时在页面上做出的更改保留
}
};
let Two = {
template: `<div>
<h1>Two</h1>
</div>`,
created() {
console.log("Two-created");
},
mounted() {
console.log("Two-mounted");
},
destroyed() {
console.log('Two-destroyed');
}
};
let App = {
template: `<div id="app">
<router-link :to="{name:'One'}">One</router-link>
<router-link :to="{name:'Two'}">Two</router-link>

<keep-alive>
<router-view></router-view>
</keep-alive>

</div>`
};

Vue.use(VueRouter);
let router = new VueRouter({
routes: [
{
name: 'One',
path: '/one',
component: One
},
{
name: 'Two',
path: '/two',
component: Two
}
]
});

let vm = new Vue({
el: "#app",
components: {
App
},
template: `<App></App>`,
router
})
</script>
</body>


标签:Vue,console,log,Two,alive,keep,let
From: https://blog.51cto.com/u_15964288/6056957

相关文章