Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

vue.js - How to store the value if I run again this vuejs javascript script? script value is again 0

If I run again this script value will be again 0. I want this component to remember "this. value" How can I keep the last value?

data () {
   return {
        value: 0
   }
},
methods: {
   count: function () {
   return this.value = this.value + 1
}
question from:https://stackoverflow.com/questions/65640796/how-to-store-the-value-if-i-run-again-this-vuejs-javascript-script-script-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

it depends on the scenario in which you want the value to persist.

if only your component is reloading (rerendering) e.g by v-for of v-if or by router you can use keep-alive to retain the value. similarly vuex store can also be used.

if you want the value to persist even after reloading entire page, you should use localStorage to store the value.

you can use computed getter and setter to change the value in localStorage like this

computed: {
    value: {
        get: () => localStorage.getItem('myCat') || 'defaultvalue';
        set: (v) => localStorage.setItem('myCat', v);
    },
},

of course you need to study the localstorage api for pro and cons as localstorage is not reactive.

on the other hand you want the value to be stored on server side then theirs a lot information to be considered, but you can use rest api to get and post value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...