1
私は私の頭の中に混じっています:なぜVue.jsのテンプレートにthis
を使用できるのか分かりません。今私はどちらを使うべきかわからない。Vueテンプレートで 'this'を使用しますか?
私はここにいくつかのケースをテスト:
new Vue({
el: "#app",
data: function() {
\t return {
\t myVar: 'test'
}
},
methods: {
returnText: function() {
\t console.log('methods returnText !');
return 'return text from methods !';
}
},
computed: {
computedProp: function() {
\t return 'computed !';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script>
<div id="app">
{{ this.myVar }}<br><!-- this works -->
{{ myVar }}<br><!-- this works -->
<button @click="myVar = 'test without this !'" type="button">
Change text</button><!-- this works --><br>
<button @click="this.myVar = 'test with this !'" type="button">
Change text (not working because of 'this')</button><!-- this NOT works -->
<br><br>
{{ computedProp }} <!-- this works -->
<br>
{{ this.computedProp }} <!-- this works -->
<br><br>
{{ returnText() }} <!-- this works -->
<br>
{{ this.returnText() }} <!-- this works -->
</div>
を勧告は何?
「this」は私がどこからでも見ることができ、なぜ結果が同じであれば5文字以上を入力するのですか? :) –
少なくとも、いくつかの場合、あなたが気づいたように、 'this'を使って問題を引き起こします。私が見つけたもう1つの場所は 'v-for'です。 Vuexでは、 '$ store ...'は 'v-for'の中にはできませんが、' $ store ... 'はうまくいきます。したがって、「これ」を使用しないことの推奨はqutie sensibleです。 –