vue2生命周期使用场景

- beforeCreate:

初始化阶段,实例和属性尚未建立,不常用。

- created:

实例已创建,属性已绑定,常用于初始化数据、发送网络请求。

created() {  
  this.initData();  
},  
methods: {  
  initData() {  
    this.list = [];  
    this.loading = true;  
    this.fetchData();  
  },  
  fetchData() {  
    // 发送网络请求获取数据  
  }  
}

- beforeMount:

模板编译成虚拟 DOM,即将挂载,不常用。

- mounted:

模板已挂载到页面,可访问和操作 DOM,常用于启动第三方插件、绑定事件监听器。同步可以获取dom,如果先子组件请求后父组件请求。
1.启动第三方插件:

mounted() {  
  this.$nextTick(() => {  
    // 确保 DOM 更新完成后再初始化插件  
    new Swiper('.swiper-container', { /* Swiper 配置项 */ });  
  });  
}

2.绑定事件监听器:

mounted() {  
  window.addEventListener('resize', this.handleResize);  
},  
beforeDestroy() {  
  window.removeEventListener('resize', this.handleResize);  
},  
methods: {  
  handleResize() {  
    // 处理窗口大小变化  
  }  
}

- beforeUpdate:

数据更新前,可访问更新前的 DOM,不常用。

- updated:

数据更新后,DOM 已更新,可用于重新计算位置或尺寸。

updated() {  
  this.$nextTick(() => {  
    // 确保 DOM 更新完成后再计算尺寸或位置  
    this.calculatePosition();  
  });  
},  
methods: {  
  calculatePosition() {  
    // 计算元素的尺寸或位置  
  }  
}

- beforeDestroy:

实例即将销毁,常用于清理定时器、解绑事件。

//清理定时器、解绑事件:
beforeDestroy() {  
  clearInterval(this.timer);  
  window.removeEventListener('resize', this.handleResize);  
},  
data() {  
  return {  
    timer: null,  
  };  
},  
// ... 其他代码

- destroyed:

实例已销毁,彻底清理资源。
关闭页面记录视频播放的时间,初始化的时候从上一次的历史开始播放

//彻底清理资源:
destroyed() {  
  // 清理组件创建时分配的所有资源  
  this.cleanup();  
},  
methods: {  
  cleanup() {  
    // 清理操作,比如销毁插件实例、解除数据绑定等  
  }  
}

- activated

===> 判断id是否相等,如果不相同发起请求
重新获取数据、重置定时器、重新绑定事件等

- deactivated

===>当组件不再活跃时,你可以在这里清理一些资源
取消请求、清除定时器、解绑事件等

<template>  
  <div>  
    <h1>My Cached Component</h1>  
    <!-- 组件的其他内容 -->  
  </div>  
</template>  
  
<script>  
export default {  
  name: 'MyCachedComponent',  
  activated() {  
    console.log('MyCachedComponent was activated!');  
    // 当组件被激活时,你可以在这里执行一些操作  
    // 比如,重新获取数据、重置定时器、重新绑定事件等  
  },  
  deactivated() {  
    console.log('MyCachedComponent was deactivated!');  
    // 当组件不再活跃时,你可以在这里清理一些资源  
    // 比如,取消请求、清除定时器、解绑事件等  
  },  
  // ... 其他选项和生命周期钩子  
};  
</script>

在路由中的使用 在你的路由配置中,你不需要特别指定某个路由是否使用 ,因为这是在模板层面决定的。你只需要在模板中包裹 组件即可:

<template>  
  <div id="app">  
    <keep-alive>  
      <router-view></router-view>  
    </keep-alive>  
  </div>  
</template>  
  
<script>  
// ...  
</script>

但如果你想对某些路由使用 <keep-alive>,而对其他不使用,你可以结合 <router-view> 的 key 属性来实现:

<template>  
  <div id="app">  
    <keep-alive>  
      <router-view v-if="$route.meta.keepAlive"></router-view>  
    </keep-alive>  
    <router-view v-if="!$route.meta.keepAlive"></router-view>  
  </div>  
</template>  
<script>  
// ...  
</script>

然后,在你的路由配置中为每个路由添加一个 meta 字段来指定是否使用 <keep-alive>

const router = new VueRouter({  
  routes: [  
    {  
      path: '/cached',  
      component: () => import('./MyCachedComponent.vue'),  
      meta: { keepAlive: true }  
    },  
    {  
      path: '/not-cached',  
      component: () => import('./MyNotCachedComponent.vue'),  
      meta: { keepAlive: false }  
    }  
    // ... 其他路由  
  ]  
});

这样,只有标记为 keepAlive: true 的路由组件才会被 <keep-alive> 包裹,并在它们被切换时触发 activated 和 deactivated 钩子。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中,生命周期钩子函数发生了一些变化。下面是一个示例,展示了Vue 3中常用的生命周期钩子函数: ```vue <template> <div> <h2>Vue 3 生命周期示例</h2> <p>{{ message }}</p> </div> </template> <script> import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'; export default { name: 'LifecycleExample', setup() { const message = ref('Hello, Vue 3!'); // 在组件挂载之前调用 onBeforeMount(() => { console.log('组件将要挂载'); }); // 在组件挂载之后调用 onMounted(() => { console.log('组件已经挂载'); }); // 在组件更新之前调用 onBeforeUpdate(() => { console.log('组件将要更新'); }); // 在组件更新之后调用 onUpdated(() => { console.log('组件已经更新'); }); // 在组件卸载之前调用 onBeforeUnmount(() => { console.log('组件将要卸载'); }); // 在组件卸载之后调用 onUnmounted(() => { console.log('组件已经卸载'); }); return { message }; } }; </script> <style scoped> h2 { color: #42b983; } </style> ``` 在这个示例中,我们使用了`setup`函数来设置组件的逻辑。通过`import`语句导入了Vue 3中的生命周期钩子函数,包括`onBeforeMount`、`onMounted`、`onBeforeUpdate`、`onUpdated`、`onBeforeUnmount`和`onUnmounted`。每个生命周期钩子函数都有一个对应的回调函数,可以在其中执行需要的操作。 在示例中,我们通过打印信息到控制台来展示每个生命周期钩子函数被调用的时机。同时,在模板中使用了一个响应式变量`message`,并将其显示在页面上。 这只是一个简单的示例,你可以根据需要在不同的生命周期钩子函数中添加自己的逻辑。请注意,Vue 3中的生命周期钩子函数已经改名为`onXXX`,与Vue 2中的生命周期钩子函数名有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值