Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 'this' in Vue template?

Tags:

vue.js

vuejs2

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 ?

like image 430
Happyriri Avatar asked Apr 03 '17 15:04

Happyriri


People also ask

What is REF () in Vue?

Ref s are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.

How do I reference an element in Vue?

Referencing DOM Elements in Vue # If we want to reference a DOM element, we can use the ref attribute in Vue. Vue can store references to DOM elements in a property called $ref . The first thing we have to do, is add a ref attribute to the element we want to reference in our Javascript.

What is Vue template tag?

In Vue, templating is the main way we create reusable components. We can use templates to take data, and turn it into real elements on a screen that users can see.

How do you use props in Vue?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.


1 Answers

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://vuejs.org/v2/guide/instance.html

like image 90
Derian André Avatar answered Sep 27 '22 19:09

Derian André