vue-router 导航到相同的路由并重新运行挂载钩子

Pat*_*ler 2 vue-router vuejs2

如何使用路由器链接导航到当前路线并重新运行挂载钩子?

HTML

<!-- Include the library in the page -->
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>

<!-- App -->
<div id="app">
  <nav>
    <router-link :to="{ name: 'home' }" exact>Home</router-link>
       <router-link :to="{ name: 'about' }" @click.native.prevent="router.push({ name: 'about' })">About</router-link>
  </nav>

  <router-view :key="$route.fullPath"></router-view>
</div>
Run Code Online (Sandbox Code Playgroud)

JS

console.clear()
console.log('Yes! We are using Vue version', Vue.version)

Vue.use(VueRouter)

const Home = {
    template: `<h1>Home</h1>`,
}

const About = {
    template: `<h1>{{new Date()}}</h1>`,
  mounted(){
    console.log('mounted')
  }
}
const routes = [
    { path: '/', name: 'home', component: Home },
  { path: '/about', name: 'about', component: About },
]
const router = new VueRouter({
    routes,
})
// New VueJS instance
var app = new Vue({
    // CSS selector of the root DOM element
  el: '#app',
  // Inject the router into the app
  router,
})
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,如果我导航到“关于”,它会显示新日期的时间戳并记录“已安装”。但是,如果我已经在 /about 上,单击 about 链接什么也不做。我想在单击“关于”时重新运行整个组件生命周期,即使我已经点击了它。

Ede*_*íaz 8

<router-view>每当用户单击您的关于页面时,您都需要更改元素中的键,这将强制安装挂钩:

<template>
  <div id="app">
    <router-link @click.native="updateViewKey" :to="{ name: 'about' }">About</router-link>

    <router-view :key="viewKey"></router-view>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      viewKey: 1
    };
  },
  methods: {
    updateViewKey() {
      this.viewKey+=1;
    }
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)