[英]Vue-router: Using component method within the router
我的第一個Vue項目,我想在每個路由器調用上運行加載效果。 我做了一個Loading
組件:
<template>
<b-loading :is-full-page="isFullPage" :active.sync="isLoading" :can-cancel="true"></b-loading>
</template>
<script>
export default {
data() {
return {
isLoading: false,
isFullPage: true
}
},
methods: {
openLoading() {
this.isLoading = true
setTimeout(() => {
this.isLoading = false
}, 10 * 1000)
}
}
}
</script>
我想這樣放置在路由器中:
router.beforeEach((to, from, next) => {
if (to.name) {
Loading.openLoading()
}
next()
}
但是我得到了這個錯誤:
TypeError:“ _ components_includes_Loading__WEBPACK_IMPORTED_MODULE_9 __。default.openLoading不是函數”
我該怎么辦?
Vuex是一個好點。 但為簡單起見,您可以在組件中觀察$route
,並在$route
更改時向您顯示加載程序,如下所示:
...
watch: {
'$route'() {
this.openLoading()
},
},
...
我認為這是快速而簡短的解決方案。
我認為您不能訪問導航保護( beforeEach
)中的組件方法,我建議您使用Vuex(這是用於數據管理的vue插件),然后使isLoading
成為全局變量,因此在每次路線導航之前,您都應該做同樣的事情。這是你可以做到的:
當然,你需要安裝Vuex
先用npm i vuex
...之后:
在您要初始化Vue實例的主文件上 :
import Vue from 'vue'
import Vuex from 'vue'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
isLoading: false,
},
mutations: {
openLoading(state) {
state.isLoading = true
setTimeout(() => {
state.isLoading = false
}, 10000)
},
},
})
// if your router is on a separated file just export the store and import it there
const router = new VueRouter({
routes: [
{
// ...
},
],
})
router.beforeEach((to, from, next) => {
if (to.name) {
store.commit('openLoading')
}
next()
})
new Vue({
/// ....
router,
store,
})
在您的組件中:
<b-loading :is-full-page="isFullPage" :active.sync="$store.state.isLoading" :can-cancel="true"></b-loading>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.