[英]Vue Router & Vuex : Getters are undefined on page refresh
I want to create a middleware according to the tickets present in the getters of a store我想根据商店的 getter 中存在的票创建一个中间件
I first initialize Vuejs with a query to generate my state我首先使用查询初始化 Vuejs 以生成我的 state
TicketStore.js 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")
})
})
})
}
Init in main.js在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')
This way works even if I do not think it's the most suitable即使我认为它不是最合适的,这种方式也有效
Now I want to stop the navigation if the ticket does not exist;现在,如果票不存在,我想停止导航; so i created a middleware in my routes.js
所以我在我的routes.js中创建了一个中间件
I first tried:我第一次尝试:
{
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)
}
}
},
This way works but if I reload the page, const ticket
is not defined这种方式有效,但如果我重新加载页面,则未定义
const ticket
So I searched;所以我搜索了; I came across multiple discussions, never really helped me, like this one Vuex store is undefined in vue-router
我遇到了多次讨论,从来没有真正帮助过我,就像这个Vuex 商店在 vue-router 中未定义
I try this too我也试试这个
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 */
}
Without success: this way doesnt work;没有成功:这种方式行不通; but i have the ticket in my console on reload
但我在重新加载时在控制台中有票
My goal is to stop navigation if the ticket does not exist, even if the page has been reloaded我的目标是在票不存在时停止导航,即使页面已重新加载
Thank you for your help谢谢您的帮助
You should define tickets
as an empty array by default in store.默认情况下,您应该将
tickets
定义为存储中的空数组。 Because for now it looks like you try get some data from store till it's not exist.因为现在看起来你尝试从存储中获取一些数据,直到它不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.