vue-router navigate to the same route and re-run mounted hook

為{幸葍}努か 提交于 2021-02-19 08:20:15

问题


How can I naviagte to the current route using router-link and re-run mounted hook?

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>

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,
})

In the above example, if I navigate to 'About' it shows the timestamp from new Date and logs 'mounted'. However, if I'm already on /about, clicking the about link does nothing. I want to re-run the whole component lifecycle when clicking 'About', even if I'm already hit it.


回答1:


You'll need to change the key in the <router-view> element whenever the user clicks your about page, that will force the mounted hook:

<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>


来源:https://stackoverflow.com/questions/57711554/vue-router-navigate-to-the-same-route-and-re-run-mounted-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!