为什么路由更新时异步组件不会改变?

时间:2019-09-09 21:29:12

标签: vue.js vuejs2 vue-router

我正在async components中使用my code on CodeSandbox(如下所示)。当我在goto product-2之后单击goto product-1时,什么也没有发生。我希望<product-item>组件会根据所单击的组件而改变,但是只有URL会改变。我什至有一个beforeRouteUpdate挂钩函数。我该如何解决?

// main.js
import Vue from "vue";
import App from "./App.vue";
import VueRouter from 'vue-router';
import ProductPage from './product-page.vue';

Vue.use(VueRouter);
Vue.config.productionTip = false;

const routes = [
  { path: '/:productId', component: ProductPage },
]

const router = new VueRouter({
  routes // short for `routes: routes`
})

new Vue({
  router,  
  render: h => h(App)
}).$mount("#app");

// App.vue
<template>
  <div id="app">
    <router-link to="/product-1">goto product1</router-link>
    <br>
    <br>
    <router-link to="/product-2">goto product2</router-link>

    <div>Router view:</div>
    <router-view :key="$route.params.productId"></router-view>
  </div>
</template>
// product-page.vue
<template>
  <div>
    <product-item></product-item>
  </div>
</template>

<script>
export default {
  name: "product-page",
  components: {
    ProductItem: () => ({
      component: import("./product-item.vue"),
      loading: { template: "<div>loading....</div>" }
    })
  }
};
</script>
<template>
  <div>
    product item: {{product}}
  </div>
</template>

<script>

export default {
  name: "ProductItem",
  mounted: function () {
    this.product = this.$route.params.productId;
  },
  beforeRouteUpdate: function(to, from, next) {
    this.product = to.params.productId;
    next();
  },
  data: function () {
    return {
      product: null
    }
  },
};

</script>

1 个答案:

答案 0 :(得分:1)

问题是路由路径(即/:productId)在/product-1/product-2的链接之间实际上没有改变(即使参数值),因此router-view不会重新呈现。

解决方法是根据key参数router-view productId

<router-view :key="$route.params.productId" />

Edit Refreshing router-view on parameter change