vue keep-alive以及activated,deactivated生命周期的用法和created钩子的区别

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

也就是activated 和 deactivated 必要和<keep-alive>配套使用才会生效。

而当组件使用keep-alive的时候created钩子函数只会被执行一次。

 

注意:当在activated钩子里面使用axios调用接口的时候且activated钩子里面的参数没有任何的改动的时候axios调用的接口只会被执行一次。如果activated里面的相关参数发生变化的时候axios调用的接口会被再一次执行(找不到相关的文档资料说明,求链接)。这个特性可以用来减少接口的调用。

 

示例代码:

创建一个A组件(E:\webProjiect\vuetest\test\src\components\A\index.vue)

<template>
    <div>
        <h1>我是A组件</h1>
    </div>
</template>

<script>
    export default {
        name: "index",
        created(){
            console.log("created");
        },
        activated(){
            console.log("activated");
        },
        deactivated(){
            console.log("deactivated");
        }
    }
</script>

<style scoped>

</style>

创建一个B组件(E:\webProjiect\vuetest\test\src\components\B\index.vue)

<template>
    <div>
        <h1>我是B组件</h1>
    </div>
</template>

<script>
    export default {
        name: "index"
    }
</script>

<style scoped>

</style>

修改App.vue文件

<template>
  <div id="app">
    <router-link to="/a">切换到a</router-link>
    <span>-----</span>
    <router-link to="/b">切换到b</router-link>
    <keep-alive>
      <!-- 路由匹配到的组件将渲染在这里 -->
      <router-view></router-view>
    </keep-alive>

  </div>
</template>

<script>

export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

修改mian.js文件

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'

import A from './components/A'
import B from './components/B'


Vue.use(VueRouter)

Vue.config.productionTip = false


const routes = [
  { path: '/a', component: A },
  { path: '/b', component: B }
]

// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

当第一次点击切换到A的时候,调用了A组件的create和activeted钩子

点击切换到B的时候执行了deactivated钩子函数

点击切换到A的时候执行了activeted钩子函数

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值