【发布时间】:2017-08-10 14:04:52
【问题描述】:
当我尝试从fnTwo() 和fnThree() 访问this.perMonth 但在fnOne() 中工作时,我得到了undefined 的价值。我可以从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)
},
]
}
}
【问题讨论】:
-
你可以使用计算属性:vuejs.org/v2/guide/computed.html
标签: javascript vue.js vuejs2 vue-component