我想根据商店的吸气剂中存在的票证创建中间件
我首先使用查询初始化Vuejs以生成我的状态
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 store is undefined in 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 */
}
没有成功:这种方式行不通;但是我在重新加载控制台的票证
我的目标是即使票证不存在,即使页面已重新加载,也要停止导航
谢谢您的帮助
答案 0 :(得分:0)
您应该在存储区中默认将tickets
定义为空数组。
因为现在看来您尝试从存储中获取一些数据,直到它们不存在。