【问题标题】:How to set a property to an object that defined in vue js data?如何将属性设置为在 vue js 数据中定义的对象?
【发布时间】:2019-09-02 21:27:13
【问题描述】:

我正在尝试将属性设置为使用原型在数据中定义的空对象,但我收到一个错误,即对象未定义,我在使用“原型”时看到错误,我必须做什么?

这适用于 vue@2.6.10,也使用了 vue-router@3.1.3 和 vuex@3.1.1。 下面的代码是导入另一个组件的一部分。

<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>

当我编辑输入时,我在控制台上收到此错误: “TypeError:无法设置未定义的属性 'firstRealName' ...”

【问题讨论】:

  • this.static.prototype 是什么? watch: { 'RealName': function(curr, prev){ this.static.prototype.firstRealName = this.static.firstRealName | prev // -- Ttrouble -- console.log(this.static.firstRealName + ': ' + prev +' =&gt; ' + curr) } }
  • @Omer 它保留至少改变一次的任何变量的第一个值
  • this.static.prototype 是未定义的,所以你不能做this.static.prototype.firstRealName
  • @DecadeMoon 是的,但为什么呢?通常它必须将“firstRealName”的属性添加到“静态”对象。如果你检查这个你可以看到this.static被定义:console.log(this.static)

标签: javascript vue.js prototype


【解决方案1】:

代替

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

你可以使用

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

文档here

【讨论】:

    【解决方案2】:

    this.static.prototype 未定义。您已将 static 初始化为空对象 {},它没有定义这样的 prototype 属性。因此你不能做this.static.prototype.firstRealName

    this.static.prototype.firstRealName = this.static.firstRealName
                ^                                     ^
                undefined                             undefined
    

    访问对象的未定义属性很好,就像在this.static.firstRealName 中一样,但是您不能像在this.static.prototype.firstRealName 中那样访问undefined 对象的属性。您无法访问未定义对象 (prototype) 的属性 firstRealName

    您需要预先定义属性:

    data() {
      return {
        Email: null,
        RealName: null,
        Ncode: null,
        City: null,
        Education: null,
        Phone: null,
        static: {
          prototype: {}  // need to define it up front
        }
      };
    },
    

    记住 Vue 中的 change detection caveats

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2019-03-19
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2017-11-03
      相关资源
      最近更新 更多