vue tabs 页签切换时 怎么才可以不刷新路由呢
时间: 2024-12-18 21:19:41 浏览: 42
在Vue.js中,当你想要创建一个带有tabs页签的组件,并且希望在切换时避免页面刷新(即保持当前路由不变),你可以使用`v-router-view`和`vuex`来管理路由状态。以下是实现步骤:
1. **设置`<router-view>`**:
将`<router-view>`标签放在每个tab内部,这样每个tab都会显示对应的路由内容。
```html
<!-- Tab页 -->
<template>
<div>
<ul class="nav nav-tabs">
<li v-for="(item, index) in tabs" :key="index" @click="switchTab(index)">
<a :href="'#' + item.name">{{ item.label }}</a>
</li>
</ul>
<router-view :key="currentTabName"></router-view>
</div>
</template>
```
2. **管理路由状态**:
使用Vuex,创建一个store来存储当前选中的tab信息。当点击新的tab时,通过`dispatch`方法更新store。
```js
// store/index.js
import { mapState } from 'vuex';
export default {
state() {
return {
currentTabName: null,
};
},
mutations: {
switchTab(state, index) {
state.currentTabName = `tab-${index}`;
},
},
getters: {
...mapState(['currentTabName']),
},
};
```
3. **监听store变化并渲染内容**:
在组件的`created()`或`mounted()`钩子中,使用`watch`或` computed`属性监听store的变化,然后动态地切换`<router-view>`的内容。
```js
<script>
import { mapState } from 'vuex';
export default {
//...
created() {
this.$store.watch(
(state) => state.currentTabName,
(newVal) => {
if (newVal !== this.currentTabName) {
this.currentTabName = newVal;
this.$router.push(`/your-routes/${newVal}`);
}
},
{ immediate: true }
);
},
//...
}
</script>
```
现在,当你在vue tabs中切换时,页面内容会根据store中存储的路由名进行渲染,而不会导致整个页面的刷新。
阅读全文
相关推荐
















