Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue钩子函数

作者:伤哖铱旧   发布日期:2025-08-28   浏览:54

// Vue 钩子函数示例

// 创建一个 Vue 实例
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  // 在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用
  beforeCreate() {
    console.log('beforeCreate: ', this.$el); // undefined
    console.log('beforeCreate: ', this.message); // undefined
  },
  // 在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。
  created() {
    console.log('created: ', this.$el); // undefined
    console.log('created: ', this.message); // Hello Vue!
  },
  // 在挂载开始之前被调用:相关的 render 函数首次被调用。
  beforeMount() {
    console.log('beforeMount: ', this.$el); // undefined
    console.log('beforeMount: ', document.getElementById('app').innerHTML); // <div id="app"></div>
  },
  // 在实例挂载到 DOM 后调用,此时 el 被替换成了通过 template 或 render 函数生成的元素。
  mounted() {
    console.log('mounted: ', this.$el); // <div id="app">Hello Vue!</div>
    console.log('mounted: ', document.getElementById('app').innerHTML); // Hello Vue!
  },
  // 数据更新时调用,发生在虚拟 DOM 打补丁之前。这里适合在更新之前访问现有的 DOM,比如手动移除已添加的事件监听器。
  beforeUpdate() {
    console.log('beforeUpdate');
  },
  // 由于数据更改导致的虚拟 DOM 重新渲染和打补丁,在这之后会调用该钩子。
  updated() {
    console.log('updated');
  },
  // 实例销毁之前调用。在这一步,实例仍然完全可用。
  beforeDestroy() {
    console.log('beforeDestroy');
  },
  // 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。
  destroyed() {
    console.log('destroyed');
  }
});

解释说明:

  • beforeCreate: 在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。此时 this 还没有对 datamethods 进行初始化,所以 this.messageundefined
  • created: 在实例创建完成后被立即调用。此时 datamethods 已经被初始化,但还没有挂载到 DOM 上。
  • beforeMount: 在挂载开始之前被调用,此时模板已经被编译,但还未挂载到页面上。
  • mounted: 在实例挂载到 DOM 后调用,此时可以操作 DOM 元素。
  • beforeUpdate: 在数据更新时调用,发生在虚拟 DOM 打补丁之前。
  • updated: 在数据更新导致的虚拟 DOM 重新渲染和打补丁之后调用。
  • beforeDestroy: 在实例销毁之前调用,此时实例仍然完全可用。
  • destroyed: 在实例销毁后调用,此时所有绑定和子实例都被销毁。

以上代码展示了 Vue 生命周期中的各个钩子函数及其调用顺序。

上一篇:vue 插件

下一篇:vue项目搭建

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站