[Vuejs]-Vue computed cannot get the the attributes in the object

0👍

You cannot define computed getters with dot notation like you can watchers. Here’s a fiddle of that not working, where you can see the error in the console reads:

Cannot read property ‘reference’ of undefined.

Also, it appears that you are attempting to define a computed property that already exists as a property defined in the data method. In this fiddle, you can see that that also won’t work. The value defined in the data method takes precedence over the computed property definition.


Anyways, from your example, I don’t see why you need to create a computed property on a nested object property at all.

Just use a normal definition for a computed property:

const store = new Vuex.Store({
  state: {
    reference: '',
  },
  mutations: {
    updateReference(state, reference) {
      state.reference = reference;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    reference: {
      get() {
        return this.$store.state.reference;
      },
      set(val) {
      	this.$store.commit('updateReference', val);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.min.js"></script>

<div id="app">
  <input type="text" v-model="reference">
  {{ $store.state.reference }}
</div>

If you really need to set the value of data.reference, then there are many ways you could make that happen. One would be to turn it into a computed property as well:

const store = new Vuex.Store({
  state: {
    reference: '',
  },
  mutations: {
    updateReference(state, reference) {
      state.reference = reference;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    reference: {
      get() {
        return this.$store.state.reference;
      },
      set(val) {
      	this.$store.commit('updateReference', val);
      }
    },
    data() {
      return { reference: this.reference };
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.min.js"></script>

<div id="app">
  <input type="text" v-model="reference">
  <div>data.reference: {{ data.reference }}</div>
  <div>$store.state.reference: {{ $store.state.reference }}</div>
</div>

Leave a comment