gpt4 book ai didi

vue.js - 在不重新安装组件的情况下更新 Vue Router?

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:01 25 4
gpt4 key购买 nike

我有一个从 URL 路径继承 activeTab 路由参数的页面。因此,在我的页面上,我可以导航到 /home/ 并在主页选项卡中加载,或者在 /somethingElse 中我可以在页面模板的选项卡视口(viewport)中加载不同的选项卡.

要更新选项卡,我正在使用:

updateTab(tab) {
this.activeTab = tab
this.$router.push(tab)
}

当我执行此操作时,屏幕会闪烁,并且我的 mounted() 函数会在每个组件中重新执行,从而触发只应在应用程序的第一个条目上触发的动画点。

这更接近所需的行为,其中选项卡发生变化,我没有看到闪烁或重新安装组件:

updateTab(tab) {
this.activeTab = tab
history.pushState({}, '', tab)
}

但是,将 activeTab 直接插入历史记录似乎会阻止“后退”按钮正确恢复之前的状态。

如何在不重新安装所有组件的情况下更新 Vue 路由器的路径?

最佳答案

当router的路径改变时,组件会重新挂载,如果只想挂载一次组件,可以试试vue自带的组件keep-alive,只会触发它的activated hook和停用的钩子(Hook)。你可以在这两个钩子(Hook)中做一些事情。

html:

<div id="app">
<router-link to="/link-one">link-one</router-link>
<router-link to="/link-two">link-two</router-link>
<keep-alive>
<router-view>

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

JavaScript:

Vue.use(VueRouter);
function createLink(path) {
let routePath = '/' + path;
return {
path: routePath,
component: {
name: path,
template: '<span>{{path}} mountedTimes:{{mountedTimes}}, activatedTimes: {{activatedTimes}}</span>',
data() {
return {
mountedTimes: 0,
activatedTimes: 0,
path: routePath
}
},
mounted() {
console.log('mounted')
this.mountedTimes++;
},
activated() {
this.activatedTimes++;
}
}
}
}
const routes = [createLink('link-one'), createLink('link-two')];
const router = new VueRouter({
routes
})
const app = new Vue({
el: "#app",
router
})

CodePen

关于vue.js - 在不重新安装组件的情况下更新 Vue Router?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com