开发者问题收集

Vue.js:无法从函数/方法访问数据

2017-08-10
9486

当我尝试从 fnTwo()fnThree() 访问 this.perMonth 时,我得到的值为 undefined ,但在 fnOne() 中却可以。我可以从 data(){ 运行一个函数,并可以返回一些值,但无法返回 data(){ 中的值,例如 this.perMonth (检查 fnThree()

Vue.component('BuySubscription', {
  template: '#buy-subscription',
  data() {
    return {
      perMonth: 19,
      valFromFnTwo: this.fnTwo(),
      valFromFnThree: this.fnThree()
    }
  },
  methods: {
    fnOne() {
      console.log("from fnOne: get data > perMonth: " + this.perMonth);
      return this.perMonth
    },
    fnTwo() {
      console.log("from fnTwo: get data > perMonth : " + this.perMonth);
      return this.perMonth
    },
    fnThree() {
      console.log("from fnThree: get data > perMonth " + this.perMonth);
      console.log("from fnThree: get data > valFromFnTwo: " + this.valFromFnTwo);
      return 123 // retruns static value
    }
  }
});

new Vue({
  el: '#app',
});
body { font-family: arial; font-size: 12px}
p {margin: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>

<div id="app" class="col-lg-6 d-flex align-items-center">
  <buy-subscription></buy-subscription>
</div>

<script type="text/x-template" id="buy-subscription">
  <div>
    <p>value from data > perMonth: {{perMonth}}</p>
    <p>value from data > valFromFnTwo:  {{valFromFnTwo}} <span style="color: red"> <-- getting Undefined here (see console)</span></p>
    <p>value from fnOne(): {{fnOne()}}</p>
    <p>value from fnTwo(): {{fnTwo()}}</p>
    <p>value from fnThree(): {{fnThree()}}</p>
  </div>
</script>

此外,请考虑我是否有我想处理的嵌套数据数组:

  data() {
    return {
      perMonth: 19,
      someVarViaFns: [
        {
          valFromFnTwo: this.fnTwo(1),
          valFromFnThree: this.fnThree(2) 
        },        
        {
          valFromFnTwo: this.fnTwo(5),
          valFromFnThree: this.fnThree(9) 
        },
      ]
    }
  }
2个回答

data 方法中调用 Vue 实例的方法存在问题,因为尚未设置数据属性。因此,这些方法中对数据属性的任何引用(在您的例子中为 this.perMonth )都将返回 undefined

改为在 createdmounted 钩子中设置 valFromFnTwovalFromFnThree 的值。这些钩子在 data 方法返回后触发,因此对数据属性的引用将按预期工作。

data() {
  return {
    perMonth: 19,
    valFromFnTwo: null,
    valFromFnThree: null
  }
},
mounted() {
  this.valFromFnTwo = this.fnTwo();
  this.valFromFnThree = this.fnThree();
}
thanksd
2017-08-10

我认为您遇到此问题是因为 JS 引擎的 提升 行为。

不要在数据中声明它,而是使用计算属性:

computed: {
  fnTwo() {
    // you can do other operations here also
    // the currency variables is just an example. not mandatory
    let currency = 'usd';

    return "value from fnTwo: " + this.perMonth + ' ' + currency;
  }
}

然后您可以在模板中呈现它 <p>{{ fnTwo }}</p> 甚至 <p>{{ fnTwo()</p> 都应该可以工作。

Christian Ahidjo
2017-08-10