前提:

        最近做的项目需求有5个tab切换,刷新时需要停留在当前的tab页;

第一种方法:缓存本地实现,刷新后取sessionStorage存的值(只是切换了tab,没有跳转路由)

vue页面:

<template>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="User" name="first">User</el-tab-pane>
    <el-tab-pane label="Config" name="second">Config</el-tab-pane>
    <el-tab-pane label="Role" name="third">Role</el-tab-pane>
    <el-tab-pane label="Task" name="fourth">Task</el-tab-pane>
  </el-tabs>
</template>

ts代码: 

<script lang="ts" setup>
import { ref } from 'vue'

const activeName = ref(sessionStorage.getItem('activeName')?sessionStorage.getItem('activeName'):'first');
const handleClick = (tab: any) => {
  sessionStorage.getItem('activeName',tab);
}
</script>

第二种方法:参考动态修改router路由携带参数(tab切换相当于路由跳转)

vue页面:

<template>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="User" name="first">User</el-tab-pane>
    <el-tab-pane label="Config" name="second">Config</el-tab-pane>
    <el-tab-pane label="Role" name="third">Role</el-tab-pane>
    <el-tab-pane label="Task" name="fourth">Task</el-tab-pane>
  </el-tabs>
</template>

ts代码:

<script lang="ts" setup>
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const activeName = ref(route.query.activeName || 'first');
const handleClick = (tab: any) => {
    activeName.value = tab;
    router.push({
        query:{
            ...route.query,
            activeName:tab
        }
    })
}
</script>

动态修改router路由所带参数(vue2写法):

转自:【VUE】动态修改router路由所带参数_张未希的博客-CSDN博客_vue 修改route参数

import { merge } from 'webpack-merge';

// 修改/新增原有参数
this.$router.push({query:merge(...this.$route.query,{'key','value'})});

// 替换所有参数
this.$router.push({query:merge({},{'key','value'})});

Logo

前往低代码交流专区

更多推荐