我得到的值作爲undefined
當我嘗試從fnTwo()
和fnThree()
訪問this.perMonth
但fnOne()
工作訪問數據。我可以運行一個函數從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)
},
]
}
}
您可以使用計算屬性:https://vuejs.org/v2/guide/computed.html – Tomer