Search code examples
javascriptvue.jsprototype

How to set a property to an object that defined in vue js data?


I'm tring to set a property to an empty object that defined in data by using prototype, but I got an error that the object is undefined, I see error just when using "prototype", what I had to do?

this is for vue@2.6.10 also vue-router@3.1.3 and vuex@3.1.1 are used. The below code is part of a component that imported in another.

<template>
  <input class="input" v-model="RealName" placeholder="Your Name"/>
  ...
</template>
<script>
export default {
  name: "Person",
  data() {
    return {
      Email: null,
      RealName: null,
      Ncode: null,
      City: null,
      Education: null,
      Phone: null,
      static: {}
    }
  },
  watch: {
    RealName: function(changed, lastOne){

      this.static.prototype.firstRealName = this.static.firstRealName | lastOne // -- Ttrouble -- 

      console.log(this.static.firstRealName + ': ' + lastOne +' => ' + changed)
    }
  }
};
</script>

When I edit the input I got this error on console: “TypeError: Cannot set property 'firstRealName' of undefined ...”


Solution

  • Instead of

    this.static.prototype.firstRealName = this.static.firstRealName | lastOne
    

    you can use

    this.$set(this.static, "firstRealName", this.static.firstRealName | lastOne);
    

    docs here