まずこちらに検証環境を用意しています。
https://vue-study01.stackblitz.io
Vue.data に関する挙動についての質問となります。
問題を単純化したコードをいかに示します。
- index.html
html
1<div id="app"> 2 <test yes_or_no="yes"></test> 3</div>
- index.js
js
1import Vue from 'vue' 2 3Vue.component('test', { 4 props:{ 5 yes_or_no:{ 6 type:String, 7 required:true, 8 } 9 }, 10 // これを復活させると求める挙動となる 11 // created(){ 12 // this.expectTrue=this.computedValue; 13 // }, 14 data(){ 15 console.log('this.yes_or_no = ',this.yes_or_no) 16 console.log('this.computedValue = ',this.computedValue) 17 return { 18 expectTrue: this.computedValue 19 } 20 }, 21 computed:{ 22 computedValue(){ 23 return this.yes_or_no === 'yes' 24 } 25 }, 26 template: '<b>{{expectTrue}}</b>' 27}) 28 29const App = new Vue({ 30 el: '#app' 31})
- console出力
this.yes_or_no = yes this.computedValue = undefined
期待する結果としては画面上にtrueが出ることなのですが出力されません。
理由としてはdata内の初期化に算出プロパティが使えないためだと推察できるのですが、
状況によってはdata内で算出プロパティが使えるようです。(とはいえdata内で算出プロパティを動かすパターンは単純化で再現できませんでした)
状況によってdata内で算出プロパティが動くときと動かないときがある理由をご教授おいただけないでしょうか?
(そもそもVue.jsにおいてdata内で算出プロパティを使うのは禁止だったりしますでしょうか?)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。