gpt4 book ai didi

javascript - Vue 路由器和 Vuex : Getters are undefined on page refresh

转载 作者:行者123 更新时间:2023-12-02 22:40:34 24 4
gpt4 key购买 nike

我想根据商店的 getter 中存在的票证创建一个中间件

我首先使用查询初始化 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")
})
})
})
}

ma​​in.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 */
}

没有成功:这种方法行不通;但我在重新加载时在控制台中有票

我的目标是如果票证不存在,即使页面已重新加载,也停止导航

感谢您的帮助

最佳答案

默认情况下,您应该将 tickets 定义为 store 中的空数组。因为目前看来您尝试从存储中获取一些数据,直到它不存在为止。

关于javascript - Vue 路由器和 Vuex : Getters are undefined on page refresh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com