vue component methods code example
Example 1: vue lifecycle hooks
<script>
export default {
beforeCreate() {
console.log("beforeCreate")
},
created() {
console.log("created")
},
beforeMount() {
console.log("beforeMount")
},
mounted() {
console.log("mounted")
},
beforeUpdate() {
console.log("beforeUpdate")
},
updated() {
console.log("updated")
},
beforeDestroy() {
console.log("beforeDestroy")
},
destroyed() {
console.log("destroyed")
}
}
</script>
Example 2: vue methods
<template>
<div id="example">
<button v-on:click="greet">Greet</button>
</div>
</template>
<script>
export default {
methods: {
greet: function(event) {
// `event` is the native DOM event
alert(event.target.tagName);
}
}
};
</script>
Example 3: how to access both child event param and parent param in vue
<template>
<ul>
<product v-for="product in products"
:product="product"
@add="addToChart" />
</ul>
</template>
<script>
const Product = {
props: ["product"],
render(h) {
return h("li", { on: { click: this.click } }, this.product);
},
methods: {
click() {
this.$emit("add", { product: this.product, quantity: 42 });
}
}
};
export default {
data() {
return {
products: ["Foo", "Bar"]
};
},
components: {
Product
},
methods: {
addToChart({ product, quantity }) {
console.log(product, quantity);
}
}
}
</script>
Example 4: methods vue class component
<template>
<button v-on:click="hello">Click</button>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
// Declared as component method
hello() {
console.log('Hello World!')
}
}
</script>