0
// Template
<v-select
  :options="options"
  class="type"
  v-model="type"
  @input="changeType()"
/>

// Script
created() {
  this.type = localStorage.getItem('type')
},
methods: {
  changeType: function () {
    localStorage.setItem("type", this.type);
  }
}

When I refresh the page or get back to this page I would like to have the selected option which was previously selected. How can I do that with VueJS?

Baboo
  • 4,008
  • 3
  • 18
  • 33
json
  • 67
  • 4
  • 15
  • You can use storage to set the value before you refresh and then get back the data as soon as the refresh completes. – skr Jul 07 '21 at 08:55
  • Can you tell me more..thanks – json Jul 07 '21 at 08:58
  • are you using vuetify? – Boussadjra Brahim Jul 07 '21 at 09:00
  • You need to detect a page refresh or page change first, see : https://stackoverflow.com/questions/58495019/how-to-detect-page-is-refreshed-on-vue then before the page actually refreshed you need to save the data in storage. now when come back to the same page you load the data for that page using storage. – skr Jul 07 '21 at 09:08

1 Answers1

0

Checkout this article : Vue single page application how to retain state data when page refreshes

import Vuex from "vuex"
 
Vue.use(Vuex)
 
function storeLocalStore (state) {
    window.localStorage.setItem("userMsg",JSON.stringify(state));
}
 
export default new Vuex.Store({
    state: {
        username: "Wang Er",
        schedulename: "title",
        scheduleid: 0,
    },
    mutations: {
        storeUsername (state,name) {
            state.username = name
            storeLocalStore (state)
        },
        storeSchedulename (state,name) {
            state.schedulename = name
            storeLocalStore (state)
        },
        storeScheduleid (state,id) {
            state.scheduleid = Number(id)
            storeLocalStore (state)
        },
    }

Then when the page loads, the data is retrieved from localStorage and placed in vuex, so Wang Er is atApp.vue of created The following code is written in the hook function:

/ / Read the status information in localStorage when the page loads
localStorage.getItem("userMsg") && this.$store.replaceState(JSON.parse(localStorage.getItem("userMsg")));

/ / Save the information in vuex to localStorage when the page is refreshed
window.addEventListener("beforeunload",()=>{
    localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
})
skr
  • 1,700
  • 1
  • 15
  • 39