vue通过v-if实现tab页切换

<template>
  <div class="con">
    <el-card class="box-card">
        <!-- tab按钮 -->
      <span class="tabs" :class="{to_active:isShow === 1}" @click="handleTab(1)">tab1</span>
      <span class="tabs" :class="{to_active:isShow === 2}" @click="handleTab(2)">tab2</span>
      <span class="tabs" :class="{to_active:isShow === 3}" @click="handleTab(3)">tab3</span>
      <span class="tabs" :class="{to_active:isShow === 4}" @click="handleTab(4)">tab4</span>
      <!-- 下面的div盒子 -->
      <div v-if="isShow === 1">111111111</div>
      <div v-if="isShow === 2">222222222</div>
      <div v-if="isShow === 3">33333333</div>
      <div v-if="isShow === 4">44444444</div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShow: 1,
    };
  },
  components: {},
  methods: {
    handleTab(val) {
      this.isShow = val;
    },
  },
  computed: {},
};
</script>


<style scoped>
.to_active {
  color: #327bdc;
  font-weight: 600;
}
.tabs {
  width: 100px;
  display: inline-block;
  line-height: 40px;
}
</style>

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3 中,`n-tab-pane` 组件需要使用 `el-tabs` 组件进行包裹,而在 `el-tabs` 中可以使用 `v-model` 绑定选中的选项卡,然后可以通过监听 `change` 事件来获取当前选项卡的位置。因此,在 Vue3 中实现 `n-tab-pane` 切换时保持原来位置的功能,可以按照以下步骤进行: 1. 在 `el-tabs` 组件上添加 `v-model` 绑定选中的选项卡,并绑定一个变量,例如: ``` <el-tabs v-model="activeTab"> ``` 2. 在组件的 `mounted` 生命周期中,读取并记录当前选项卡的位置,例如: ``` mounted() { // 读取当前选项卡的位置 const position = sessionStorage.getItem(`tab${this.activeTab}Position`); // 如果有位置记录,则滚动到相应位置 if (position) { this.$nextTick(() => { const tab = this.$refs[`tab${this.activeTab}`]; tab.$el.scrollTop = position; }); } } ``` 3. 在组件的 `activated` 生命周期中,重新设置当前选项卡的位置,例如: ``` activated() { // 读取之前记录的位置 const position = sessionStorage.getItem(`tab${this.activeTab}Position`); // 如果有位置记录,则滚动到相应位置 if (position) { this.$nextTick(() => { const tab = this.$refs[`tab${this.activeTab}`]; tab.$el.scrollTop = position; }); } } ``` 4. 在 `el-tabs` 组件上添加 `change` 事件监听,例如: ``` <el-tabs v-model="activeTab" @change="handleChangeTab"> ``` 5. 在组件中定义 `handleChangeTab` 函数,用于记录当前选项卡的位置,例如: ``` handleChangeTab() { // 记录当前选项卡的位置 sessionStorage.setItem(`tab${this.activeTab}Position`, this.$refs[`tab${this.activeTab}`].$el.scrollTop); } ``` 通过以上步骤,就可以实现 `n-tab-pane` 切换时保持原来位置的功能了。需要注意的是,以上代码中的 `tab` 和 `activeTab` 都需要根据实际情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值