当页面被 vue-router 重新打开时,不会调用 VueJS 钩子挂载()

Aug*_*sto 8 javascript vue.js vue-router vuejs2

请看下面的通量,它显示了我的问题。我正在使用 vue-routerthis.$router.push浏览页面。我从 PageA 开始。

  • PageA -> PageB (mounted()PageB 被称为)

  • PageB -> PageA(返回到PageA)

  • PageA -> PageB (mounted()的 PageB 不被调用)

听起来页面(.vue 组件)没有关闭并在缓存或其他东西上维护。mounted()每次打开该页面时我都必须使用该方法,并且可能关闭该页面并清除缓存。我该如何解决?

Tur*_*ght 6

vue重新使用组件是可能的,这是预期的。
通常,您会监视路由更改并相应地更新组件状态。

要对路线更改做出反应,您可以使用beforeRouteUpdate()

const Example = Vue.extend({
  template: `
  	<div>
  		<p>This changes: '{{param}}'</p>
    </div>`,
  data(){
    return {
      param: this.$route.params.param
    };
  },
  beforeRouteUpdate(to, from, next) {
    this.param = to.params.param;
    next();
  }
});

const router = new VueRouter({
  routes: [
    {
      path: '/:param', component: Example,
    }
  ]
})
const app = new Vue({ router }).$mount('#app')
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/foo">foo</router-link><br>
  <router-link to="/bar">bar</router-link><br>
  <router-view></router-view>
</div>
Run Code Online (Sandbox Code Playgroud)

或者,您也可以观察路线并相应地更新状态:

Vue.extend({
  watch: {
    '$route'() {
      // TODO: react to navigation event.
      // params cotains the current route parameters
      console.log(this.$route.params);
    }
  },
  // ....
});
Run Code Online (Sandbox Code Playgroud)

vue-router文档有几个很好的示例:Data Fetching - Vue Router

如果您仍然想使用mounted(),您可以通过给您一个密钥来实现,router-view该密钥会在路线更改时更改,例如:

Vue.extend({
  watch: {
    '$route'() {
      // TODO: react to navigation event.
      // params cotains the current route parameters
      console.log(this.$route.params);
    }
  },
  // ....
});
Run Code Online (Sandbox Code Playgroud)

这将迫使每次都重新创建组件,因此它确实会造成性能损失 - 如果可能的话,我建议使用上面描述的路由钩子。