在Vue模板中如何使用'this'?

8

我有些糊涂了:我不知道为什么会看到在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>

什么是推荐?


6
不使用“this”是我到处看到的,为什么要多打5个字符,如果结果是相同的呢? :) - Amresh Venugopal
在某些情况下,使用this会导致问题,正如您所注意到的那样。我发现另一个地方是在v-for中。使用Vuex时,您不能在v-for内部使用this.$store...,但$store...可以正常工作。因此,不建议使用this是相当明智的建议。 - Sami Kuhmonen
2个回答

4
在模板中,你不需要使用this关键字,而是在类似mounted()created()methods等函数中使用this。所有生命周期钩子都会在此上下文中调用,指向调用Vue实例。
参考链接:https://v2.vuejs.org/v2/guide/instance.html

0

我认为v-bind的作用类似于js本地的“bind”函数,例如将函数绑定到另一个对象上,而不是我们上下文中的Vue实例(在其他情况下)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接