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 lifecycle
beforeCreate() {
// before! observe the data and props
console.log("beforeCreate")
},
// observing data and props
// init events
created() {
console.log("created")
// have access to data and props
// good time to fetch data and manipulate data on the component
},
// check if there is an "el" option and render it.
// else check if there is a template and render it but not show yet.
beforeMount() {
console.log("beforeMount")
// finish render the template and its child component
// good time to manipulate data that came back from child component
},
// render the template to the real DOM
mounted() {
console.log("mounted")
// the template is render and printed on the real DOM
// if you manipulate the data here its effect on the view that already printed
},
beforeUpdate() {
console.log("beforeUpdate")
// just before any update of the component happens
// good time to debug what the status before the change
},
// the update happens
updated() {
console.log("updated")
// good time to debug what changed
},
beforeDestroy() {
console.log("beforeDestroy")
// component before unmounted, time for update the things that happens on this component
},
// clean all events, watchers, and child components
destroyed() {
console.log("destroyed")
// component unmounted, time for clean ups
}
Example 3: vue watch
var vm = new Vue({
el: '#demo',
data: {
firstName: 'Foo',
lastName: 'Bar',
fullName: 'Foo Bar'
},
watch: {
firstName: function (val) {
this.fullName = val + ' ' + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + ' ' + val
}
}
})
Example 4: computed vue
// ...
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
// ...
Example 5: vue add watcher
vm.$watch('person.name.firstName', function(newValue, oldValue) {
alert('First name changed from ' + oldValue + ' to ' + newValue + '!');
});
Example 6: vue lifecycle methods
1.beforeCreate()
2.created() It's better to done some side effect in created life cycle hook //good for fetching data
3.beforeMount()
4.mounted() //it's a good to manipulate a DOM once its been mounted
5.beforeUpdate : if vue detects a change that is gonna occur in this component and it will run this before the change is updated in the DOM
6.updated ():run after the DOM has been updated and it has been rerendered