I've got some strange issues with my Nuxt.js Setup. Some States in Store arent persistent, everytime I load another view, they went back to the default value.
pages/test.vue
<template>
<section class="section">
<b-container>
<b-row>
<b-col cols=12>
<b-button @click="setTest" variant="dark">test</b-button> | {{this.$store.state.test}} |
</b-col>
</b-row>
</b-container>
</section>
</template>
<script>
export default {
name: 'test',
methods: {
setTest() {
this.$store.commit("setTest")
},
}
}
</script>
store/index.js
export const state = () => ({
test: "test"
})
export const mutations = {
setTest: (state) => state.test = 'Hello'
}
Testscenario is to hit the "test"-button who call the method with mutation-commit "setTest" which set the state to "Hello". Currently it works fine, but if I changed the view or reload the page, the state is set to default "test".
What am I doing wrong?
Alright, so the behavior is totally logic. Vuex is not supposed to be persistent.
For any persistence on the front-end, you need either:
Some of the packages here may be useful: https://github.com/vuejs/awesome-vue#persistence
If you reload your page with an F5, all your JS will be wiped and loaded again. Hence, no state will be kept since it will be a brand new page. When working with frontend frameworks, you cannot expect it to just work after a page refresh.
Same go when you do follow an href
, it is an actual real navigation. What you need to do, is to use a <nuxt-link></nuxt-link>
component, with something like to="/profile"
to let VueJS move to this URL.
NuxtLink is a Nuxt.js component and essentially a component on top of <router-link></router-link>
, which is Vue router .
TLDR: you cannot use things like window.location.href
, nor <a href="..."
. You may use the given components by either Nuxt ( nuxt-link
) or Vue's router ( router-link
), if you're using VueJS only.
Giving a read to the Vue router's documentation may be a good start to understand things a bit more !
If you're using nuxt/auth
, give a try to that one: https://auth.nuxtjs.org/api/storage/#universal-storage
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.