2017-08-10 82 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