10

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 ?

2
  • 6
    not using this is the one I see everywhere, and why type 5 chars more, if result is same. :) Commented Apr 3, 2017 at 15:52
  • At least in some cases using this causes issues, as you noticed. One other place I found is in v-for. With Vuex you can't do this.$store... within v-for but $store... works fine. So the recommendation to not use this is qutie sensible. Commented Apr 3, 2017 at 18:12

2 Answers 2

5

In template you don't need to use this, you use this in functions like mounted(), created(), or in methods, etc. All lifecycle hooks are called in this context pointing to the invoking Vue instance.

https://v2.vuejs.org/v2/guide/instance.html

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.