0

I have a component with a form for which I need to implement data autosave when entering content. How to apply an example for v-model = "titleName" to v-model = "article.title[currentLanguage]"?

P.S. currentLanguage is taken from store

<div id="app">
  Title is <input type="text" name="titleName" id="titleName" v-model="titleName">
   Title is <input type="text" name="article" id="article" 
v-model="article.title.en">
</div>

<script>
var app = new Vue({
  el:'#app',
  data: {
    titleName: '',
      article: {
        title: {
           en: null,
           ru: null
        }
     }
  },  
  computed: {
    availableLanguages() {
      return this.$store.state.languages;
    }
  },
  created() {
    this.setDefaults();
  },  
  mounted () {
   const SAVED = localStorage.getItem('content')
    if (SAVED) {
      this.titleName = SAVED
    }
  },  
  watch: {
    titleName(newTitleName) {
      localStorage.content = newTitleName;
    }
  }
</script>

https://codepen.io/pershay/pen/EJQGGO

1 Answer 1

1

Just use localStorage.setItem('titleName', newTitleName) and localStorage.getItem('titleName')

You don't need to load on mounted. Place it in the data function itself. I think this is the better way:

var app = new Vue({
  data:() => ({
    titleName: localStorage.getItem('titleName'),
    article: JSON.parse(localStorage.getItem('article'))
  }),
  watch: {
    titleName(newTitleName) {
      localStorage.setItem('titleName', newTitleName)
    },
    article(newArticle) {
        handler: function(newArticle) {
            localStorage.setItem('article', JSON.stringify(newArticle))
        },
        deep: true
    },
  }

The example above also includes a deep object watch.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But how to apply it when the v-model looks like "foo.bar"?
You need to create a computed property, something like foo_bar(){return this.foo.bar}. Then you watch that property. You can also "deep watch" the object and serialize the object before storing in the localStorage. And obviously deserialize when getting from the localStorage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.