programing

Vue Router & Vuex : 페이지 새로 고침 시 Getter가 정의되지 않음

yoursource 2022. 12. 21. 23:05
반응형

Vue Router & Vuex : 페이지 새로 고침 시 Getter가 정의되지 않음

스토어 게터에 있는 티켓에 따라 미들웨어를 만들고 싶다.

먼저 쿼리를 사용하여 Vuej를 초기화하여 상태를 생성합니다.

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')

이 방법은 가장 적합하지 않다고 생각되더라도 작동합니다.

티켓이 존재하지 않으면 네비게이션을 정지하고 싶기 때문에 루트에 미들웨어를 만들었습니다.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저장소의 빈 배열로 기본 설정됩니다.왜냐하면 지금은 존재하지 않을 때까지 상점에서 데이터를 얻으려고 하는 것 같기 때문입니다.

언급URL : https://stackoverflow.com/questions/58605042/vue-router-vuex-getters-are-undefined-on-page-refresh

반응형