[英]How to use vue-router in a reusable method
我正在嘗試能夠在我的應用程序中需要的地方重用我的代碼段。 這段代碼對vue-router的路徑做了條件。
為此,我創建了一個文件“utils.js”:
const util = {
nextStepAtelier () {
if (this.$route.path.includes(this.user.event_1.slug)) {
this.$router.push(`/events/${this.user.event_1_2.slug}/step-1`)
}
if (this.$route.path.includes(this.user.event_1_2.slug)) {
this.$router.push(`/games/game-1/step-1`)
}
}
};
export default util;
在我的step-3.vue
,我像這樣調用我的nextStepAtelier()
:
import util from '~/utils/utils'
export default {
computed: {
user() {
return this.$store.getters['auth/user']
}
},
methods: {
nexstStep() {
util.nextStepAtelier();
}
}
}
它不起作用。 我有與 view-router 相關的錯誤Cannot read property 'path' of undefined
。 看起來它沒有正確分析 vue-router。
我指定當我直接在step-3.vue
制作此代碼時,它可以工作
謝謝
您需要導入路由器,您無權訪問 js 文件中的全局$router
。 只需放在文件的頂部: import router from './router.js'
(或任何路徑)然后將$router
更改$router
router
(刪除“this”)
由於this
在您的 util 對象內部是不同的,您可以讓 nextStepAtelier 接受路由器實例作為參數,然后使用util.nextStepAtelier(this.$router)
調用它
然后你可以使用router.currentRoute
訪問當前路由(而不是this.$route
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.