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

Sye*_*yed 1 javascript vue.js vue-component vuejs2

我得到的值undefined当我尝试访问this.perMonthfnTwo()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',
});
Run Code Online (Sandbox Code Playgroud)
body { font-family: arial; font-size: 12px}
p {margin: 0}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

另外,请考虑我是否有我喜欢处理的嵌套数据数组:

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

tha*_*ksd 6

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

设置的值valFromFnTwo,并valFromFnThreecreatedmounted钩来代替。这些钩子在data方法返回后触发,因此对数据属性的引用将按预期工作。

data() {
  return {
    perMonth: 19,
    valFromFnTwo: null,
    valFromFnThree: null
  }
},
mounted() {
  this.valFromFnTwo = this.fnTwo();
  this.valFromFnThree = this.fnThree();
}
Run Code Online (Sandbox Code Playgroud)