vue.js---- keep-alive的使用

使用 is 特性来切换不同的组件的时候,为了保存不活动的组件的状态,也避免重复渲染带来的性能问题,需要使用 keey-alive 来缓存组件;

<!-- 失活的组件将会被缓存!-->

<keep-alive>

<component v-bind:is="currentTabComponent"></component>

</keep-alive>

父组件:

<template>
  <div class="all">
    <button @click="change('dog')">组件一</button> <button @click="change('pig')">组件二</button>
    <keep-alive>
      <component :is="comp"></component>
    </keep-alive>
  </div>
</template>
<script>
import dog from "../components/dog";
import pig from "../components/pig";
export default {
  data() {
    return {
      comp: "dog"
    };
  },
  components: { dog, pig },
  methods: {
    change(val) {
      this.comp = val;
    } }
};
</script>
<style lang='scss' scoped>
button {
  width: 70px;  height: 30px; margin-right: 10px;  user-select: none;
}
</style>

子组件一:

<template>
  <div style="background:blue;width:300px;height:260px;color:skyblue;">这是dog的独有场所</div>
</template>
<script>
export default {
    name:'dog',
  data() {
    return {};
  }
};
</script>

子组件二:

<template>
  <div class="all">
    <div class="title">
      <button :class="[which=='pig1'?'org':'']" @click="select('pig1')">文章一</button>
      <button :class="[which=='pig2'?'org':'']" @click="select('pig2')">文章二</button>
    </div>
    <div class="body">
      <component :is="which"></component>
    </div>
  </div>
</template>
<script>
import pig1 from "./pig1.vue";
import pig2 from "./pig2.vue";
export default {
  name: "pig",
  data() {
    return { which: "pig1" };
  },
  components: { pig1, pig2 },
  methods: {
    select(val) {
      this.which = val;
    }
  }
};
</script>

 孙子组件一,二,(就是文字不一样)

<template>
<div class="all">
    这个世界上有那么多的地方 
</div>
</template>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值