一、生命周期与钩子函数
Vue的生命周期可以大致分为三个阶段:初始化组件实例阶段、更新组件实例阶段和销毁组件实例阶段。
<template><div><p>{{ message }}</p><button @click="updateMessage">Update Message</button><button @click="destroyComponent">Destroy Component</button></div>
</template>
<script>
export default {data() {return {message: 'Hello Vue!'};},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');},methods: {updateMessage() {this.message = 'Updated Message!';},destroyComponent() {this.$destroy(); // 手动销毁组件}}
};
</script>