[英]Vue Router & Vuex : Getters are undefined on page refresh
我想根據商店的 getter 中存在的票創建一個中間件
我首先使用查詢初始化 Vuejs 以生成我的 state
TicketStore.js
const getters = {
getTickets: state => state.tickets,
getTicketById: (state) => (id) => {
return state.tickets.find(ticket => ticket.id === id)
},
//get nb of ticket for tabs
nbTicket: state => state.tickets.length
};
const actions = {
.... ,
getTicketsFromAPI({commit}) {
axios.get(api.get, {
headers: {
'Access-Control-Allow-Origin': '*'
}
})
.then((response) => {
response.data.data.forEach(function (el) {
let dateFormat = require('dateformat')
let now = new Date(el.created_at)
commit('NEW_TICKET', {
id: el.id,
name: el.name,
msg: el.body,
date: dateFormat(now, "dd/mm/yyyy à H:MM:ss")
})
})
})
}
在main.js中初始化
import Vue from 'vue'
import vuetify from './plugins/vuetify'
import routes from './routes/router.js'
import App from './pages/layout/App'
import TicketStore from '@/store/TicketStore'
Vue.config.productionTip = false
new Vue({
vuetify,
created() {
TicketStore.dispatch('getTicketsFromAPI')
},
render: h => h(App),
router: routes,
}).$mount('#app')
即使我認為它不是最合適的,這種方式也有效
現在,如果票不存在,我想停止導航; 所以我在我的routes.js中創建了一個中間件
我第一次嘗試:
{
path: '/ticket/:id', component: Ticket, name: 'ticket',
beforeEnter: (to, from, next) => {
const id = to.params.id
const ticket = TicketStore.getters.getTicketById(id)
/* eslint-disable no-console */
console.log(id, ticket, to);
/* eslint-enable no-console */
if (ticket && ticket.id === id) {
next()
} else {
next(false)
}
}
},
這種方式有效,但如果我重新加載頁面,則未定義const ticket
所以我搜索了; 我遇到了多次討論,從來沒有真正幫助過我,就像這個Vuex 商店在 vue-router 中未定義
我也試試這個
beforeEnter: (to, from, next) => {
const id = parseInt(to.params.id)
/* eslint-disable no-console */
console.log(TicketStore.state)
TicketStore.state.tickets.forEach(function (el) {
if (el.id === id) {
next()
} else {
next(false)
}
})
/* eslint-enable no-console */
}
沒有成功:這種方式行不通; 但我在重新加載時在控制台中有票
我的目標是在票不存在時停止導航,即使頁面已重新加載
謝謝您的幫助
默認情況下,您應該將tickets
定義為存儲中的空數組。 因為現在看起來你嘗試從存儲中獲取一些數據,直到它不存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.