[Vuejs]-Computed Object V-Model Is Not Updating After Change

2đź‘Ť

For me it looks like you are trying to use a computet property as a v-model and in my opinion that is not possible. The first_name object must be in the data section.

var vm = new Vue({
    el: "#app",
    data() {
      return {
        language: 'en',
        first_name: {
          en: '',
          es: ''
        },
        languageItems: [
          {
            text: 'English',
            value: 'en'
          },
          {
            text: 'Spanish',
            value: 'es'
          }
        ]
      }
    }
 });

https://jsfiddle.net/5w9n8j13/

if you now enter a value and change the language, it will be saved under the selected language.

2đź‘Ť

*Edit – re-read your question and looked at the fiddle again. You question has nothing to do with v-model or computed.

You need to add :key=”language” to your name component. Vue doe not know it needs to re-render that component because it won’t watch the language variable by default. By adding key you tell it when that variable change to re-render which then moves your [language] call to the alternate language.

<v-text-field v-model="dataObject.first_name[language]" label="First name" :key="language"></v-text-field>

Computed is used to do some calculations on data and return the result after the calculations/manipulation/modification. It does not actually store the data as a stand alone item. Typically this would be used along with a Vuex store or similar where the data is stores elsewhere and you don’t want to have to type this.$store.state.module.name everywhere.This would allow you to get and set the long-form version and locally just use name

I have made a basic fiddle that will show how to use a computed value in v-model but you can see that the computed property is setting and retiriving a seperatly stored variable in order to work.

https://jsfiddle.net/goofballtech/s3xkzh2f/7/

<div id="app">
  <input type="text" v-model="name">
  {{name}}
</div>

new Vue({
  el: "#app",
  data: {
    nameStore: ''
  },
  computed: {
    name: {
      get() {
        return this.nameStore
      },
      set(value) {
        this.nameStore = value
      },
    },
  },
  methods: {}
})

You can see there is a getter and a setter in the computed value. One updates the placeholder variable and the other retrieves the placeholders value then returns it to the location where the variable has been called.

Leave a comment