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

时间:2017-08-10 14:04:53

标签: javascript vue.js vuejs2 vue-component

当我尝试从undefinedthis.perMonth访问fnTwo()但我在fnThree()中工作时,我的价值为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>
&#13;
&#13;
&#13;

另外,请考虑我是否嵌套了我想要处理的数据数组:

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

2 个答案:

答案 0 :(得分:3)

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

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

data

答案 1 :(得分:0)

由于JS引擎的Hoisting行为,我认为你遇到了这个问题。

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

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>中呈现它,两者都应该有效。