Vue.js method

Vue methods are functions associated with Vue instances. The method is defined internallymethodsproperty. Let us see how they work.


What is the Vue.js method

Vue methods are functions associated with Vue instances.

The method is defined internallymethodsproperty:

new Vue({
  methods: {
    handleClick: function() {
      alert('test')
    }
  }
})

Or in the case of a single file component:

<script>
export default {
  methods: {
    handleClick: function() {
      alert('test')
    }
  }
}
</script>

When you need to perform an operation and attach av-onInstruction on the element to be processedMemorabilia. like this,handleClickWhen clicking on an element:

<template>
  <a @click="handleClick">Click me!</a>
</template>

Pass parameters to the Vue.js method

The method can accept parameters.

In this case, you just need to pass the parameters in the template and then

<template>
  <a @click="handleClick('something')">Click me!</a>
</template>
new Vue({
  methods: {
    handleClick: function(text) {
      alert(text)
    }
  }
})

Or in the case of a single file component:

<script>
export default {
  methods: {
    handleClick: function(text) {
      alert(text)
    }
  }
}
</script>

How to access data from methods

You can use to access any data properties of the Vue component.this.propertyName:

<template>
  <a @click="handleClick()">Click me!</a>
</template>

<script> export default { data() { return { name: ‘Flavio’ } }, methods: { handleClick: function() { console.log(this.name) } } } </script>

We don't have to usethis.data.name, Justthis.name. Vue does provide us with transparent binding. usethis.data.nameWill cause an error.

As you saw earlier in the event description, methods are closely related to events because they are used as event handlers. This method will be called every time an event occurs.

Download mine for freeVue manual


More vue tutorials: