VueJS 路由器链路不更新组件内容



Category component

<ul v-else>
<li
v-for="cat in getCategories">
<router-link :to="{ name: 'ProductsCategory', params: {category_name: cat.name}}">{{ cat.name }}</router-link>
</li>
</ul>

这工作正常,并且可以很好地重定向到正确的链接。

问题是

当它重定向时,它不会在我使用vuex时再次调用状态。

组件脚本

computed: {
getLoading () {
return this.$store.state.companyInfo.loading;
},
getCompanyBasicInfo () {
return this.$store.state.companyInfo.companyBasicInfo;
},
getCategories () {
return this.$store.state.categories.categoriesName;
},
getCategoriesLoading () {
return this.$store.state.categories.loadingState;
},
getCataegoryProducts () {
return this.$store.state.products.getCategoryProducts;
},
},
created() {
this.$store.dispatch('getCategories', this.$route.params);
this.$store.dispatch('getCategoryProductsAction', this.$route.params);
this.$store.dispatch('getCompanyBasicInfo', this.$route.params);
}

它应该调用getCategoryProductsAction由于参数router-link而调用我的 API 和过滤器。

这可能是正常的,因为此组件未被销毁,但$route参数已更改。

因此,您可以观看$route以了解更改params.category_name

watch: {
// when redirect to new category_name, this will be callback
'$route': (new, old) => {
if (new.params.category_name !== old.params.category_name) {
// reload data, same with created()
}
}
}

另请参阅: https://router.vuejs.org/guide/advanced/data-fetching.html#fetching-after-navigation

我更喜欢在 Vue.js 中使用手表生命周期。

基本上,它的作用是监视您的路线,当它发生变化时,您可以告诉它运行一个函数。

例:

watch: {
// call again the method if the route changes
'$route': 'initService'

}

最新更新