2017-08-10 76 views
0

我得到的值作为undefined当我尝试从fnTwo()fnThree()访问this.perMonthfnOne()工作访问数据。我可以运行一个函数从data(){},可以返回一些值,但不能返回在data(){}例如。 this.perMonth(检查fnThree()Vue.js:无法从功能/方法

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) 
     }, 
     ] 
    } 
    } 
+0

您可以使用计算属性:https://vuejs.org/v2/guide/computed.html – Tomer

回答

3

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

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

data() { 
    return { 
    perMonth: 19, 
    valFromFnTwo: null, 
    valFromFnThree: null 
    } 
}, 
mounted() { 
    this.valFromFnTwo = this.fnTwo(); 
    this.valFromFnThree = this.fnThree(); 
} 
+0

感谢您的帮助。你上面定义的东西现在似乎是很好的解决方案,但是如果存在嵌套的数据数组呢? – Syed

+0

您也可以在安装的挂钩中进行设置。 'this.someVarViaFns = [{valFromFnTwo:this.fnTwo(1),...},{...}]' – thanksd

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>都应该工作。

+0

这会使属性对'this.perMonth'的更改产生反应,这可能不是OP想。 – thanksd