我有些糊涂了:我不知道为什么会看到在Vue.js模板中可以使用this
。现在我不知道该使用哪个。
我在这里测试了一些情况:
new Vue({
el: "#app",
data: function() {
return {
myVar: 'test'
}
},
methods: {
returnText: function() {
console.log('methods returnText !');
return 'return text from methods !';
}
},
computed: {
computedProp: function() {
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
会导致问题,正如您所注意到的那样。我发现另一个地方是在v-for
中。使用Vuex时,您不能在v-for
内部使用this.$store...
,但$store...
可以正常工作。因此,不建议使用this
是相当明智的建议。 - Sami Kuhmonen