在 Vue 模板中使用“this"? [英] Use 'this' in Vue template?

查看:29
本文介绍了在 Vue 模板中使用“this"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在这里测试了一些案例:

new Vue({el: "#app",数据:函数(){返回 {myVar: '测试'}},方法: {返回文本:函数(){console.log('方法返回文本!');return '从方法返回文本!';}},计算:{计算道具:函数(){返回计算!";}}});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js"></script><div id="应用程序">{{ this.myVar }}<br><!-- 这有效-->{{ myVar }}<br><!-- 这有效--><button @click="myVar = 'test without this!'" type="button">更改文本</button><!-- 这有效--><br><button @click="this.myVar = 'test with this!'" type="button">更改文本(由于这个"而不起作用)</button><!-- 这不起作用--><br><br>{{computedProp }} <!-- 这有效--><br>{{ this.computedProp }} <!-- 这有效--><br><br>{{ returnText() }} <!-- 这有效--><br>{{ this.returnText() }} <!-- 这有效-->

有什么建议?

解决方案

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

I'm mixed in my head : I don't know why I see somewhere that we can use this in Vue.js template. Now I don't know which I must use.

I test some case here :

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>

What is the recommendation ?

解决方案

I assume v-bind acts like js native 'bind' function, e.g. binds function to another object, different than our context ( which is Vue instanse in other cases).

这篇关于在 Vue 模板中使用“this"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆