当前位置: 首页> 教育> 幼教 > 深圳住建局官网_wordpress国内能用吗_网络销售推广公司_合肥seo网络营销推广

深圳住建局官网_wordpress国内能用吗_网络销售推广公司_合肥seo网络营销推广

时间:2025/9/15 5:44:57来源:https://blog.csdn.net/everfoot/article/details/143433182 浏览次数:1次
深圳住建局官网_wordpress国内能用吗_网络销售推广公司_合肥seo网络营销推广

Vue3 生命周期 - 2024最新版前端秋招面试短期突击面试题【100道】 🔄

在Vue.js中,生命周期钩子是组件从创建到销毁过程中的一系列事件。理解Vue的生命周期对于掌握组件的行为和调试至关重要。Vue 3引入了Composition API,改变了生命周期函数的使用方式。以下是关于Vue 2和Vue 3生命周期的详细解释。

Vue 2 生命周期钩子 🌱

在Vue 2中,组件生命周期包括多个钩子函数,主要有:

  1. beforeCreate:实例刚被创建,数据还未初始化。
  2. created:实例创建完成,数据已初始化。
  3. beforeMount:模板渲染前,DOM还未挂载。
  4. mounted:实例已挂载,DOM已渲染。
  5. beforeUpdate:数据更新前。
  6. updated:数据更新后,DOM已更新。
  7. beforeDestroy:实例销毁前。
  8. destroyed:实例已销毁。

示例代码(Vue 2)

new Vue({el: '#app',data() {return {msg: 'Hello Vue!'};},beforeCreate() {console.log("beforeCreate,挂载了vue实例的方法,但是data没有挂载", this.msg);},created() {console.log("created,挂载了data", this.msg);},beforeMount() {console.log("data没有渲染到了页面", document.getElementById("app").innerHTML);},mounted() {console.log("mounted data渲染到了页面", document.getElementById("app").innerHTML);},beforeUpdate() {console.log("beforeUpdate数据更改导致DOM更改之前", document.getElementById("app").innerHTML);},updated() {console.log("updated数据更改导致DOM更改之后", document.getElementById("app").innerHTML);},beforeDestroy() {console.log("beforeDestroy");},destroyed() {console.log("destroyed");}
});

Vue 3 生命周期钩子 🌳

在Vue 3中,使用Composition API,生命周期钩子的使用方式发生了变化。以下是与Vue 2对应的生命周期钩子:

  1. onBeforeMount:组件渲染前。
  2. onMounted:组件已挂载。
  3. onBeforeUpdate:组件更新前。
  4. onUpdated:组件更新后。
  5. onBeforeUnmount:组件卸载前。
  6. onUnmounted:组件已卸载。

示例代码(Vue 3)

const { createApp, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, ref } = Vue;const app = createApp({setup() {const msg = ref("你好11111111111");console.log("1");onBeforeMount(() => {console.log("onBeforeMount data没有渲染到了页面", document.getElementById("app").innerHTML);});onMounted(() => {console.log("onMounted data渲染到了页面", document.getElementById("app").innerHTML);setTimeout(() => {msg.value = "hello";}, 1000);});onBeforeUpdate(() => {console.log("onBeforeUpdate");});onUpdated(() => {console.log("onUpdated");});onBeforeUnmount(() => {console.log("onBeforeUnmount");});onUnmounted(() => {console.log("onUnmounted");});return { msg };}
});app.mount('#app');

总结 📖

Vue 2 生命周期钩子

  • beforeCreatecreated:用于初始化。
  • beforeMountmounted:用于处理DOM操作。
  • beforeUpdateupdated:用于响应数据变化。
  • beforeDestroydestroyed:用于清理工作。

Vue 3 生命周期钩子

  • 引入了 setup 函数,钩子的使用方式变为函数调用,提升了灵活性。
  • 移除了 beforeCreatecreated,用 setup 替代。
  • destroy 改为了 unmount,使得语义更加明确。

理解Vue的生命周期及其在不同版本中的变化,将帮助你更好地管理组件的状态和行为,提高开发效率。在面试中能清晰地解释这些概念,将使你更具竞争力!

关键字:深圳住建局官网_wordpress国内能用吗_网络销售推广公司_合肥seo网络营销推广

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: