在 Vue 模板中使用“this”?

Hap*_*wan 8 vue.js vuejs2

我的this脑子里一片混沌:我不知道为什么我看到了我们可以在 Vue.js 模板中使用的地方。现在我不知道我必须使用哪个。

我在这里测试一些案例:

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 !';
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Ego*_*kio 0

我假设 v-bind 的行为类似于 js 原生的“绑定”函数,例如将函数绑定到另一个对象,与我们的上下文不同(在其他情况下是 Vue 实例)。