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'会导致问题,正如您注意到的那样。我发现的另一个地方是'v-for'。使用Vuex,你不能在'v-for'内执行'this。$ store ...',但'$ store ...'工作正常。所以不使用'this'的建议是合理的。 –