需求,vue项目中,点击tabs的时候,页面再刷新渲染,没点击的tab页面不渲染,
时间: 2024-03-12 07:46:26 浏览: 14
你可以尝试使用 Vue 的动态组件实现这个需求。具体来说,你可以将每个 tab 对应的内容封装成一个组件,然后在点击对应的 tab 时,动态地将该组件加载到页面中。
具体实现步骤如下:
1. 在父组件中定义一个数组,用于存储所有的 tab 内容组件:
```
<template>
<div>
<div class="tab" v-for="(tab, index) in tabs" :key="index" @click="activeTab = index">{{ tab.title }}</div>
<component :is="currentTabComponent"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
import Tab3 from './Tab3.vue'
export default {
components: {
Tab1,
Tab2,
Tab3
},
data() {
return {
tabs: [
{
title: 'Tab 1',
component: Tab1
},
{
title: 'Tab 2',
component: Tab2
},
{
title: 'Tab 3',
component: Tab3
}
],
activeTab: 0
}
},
computed: {
currentTabComponent() {
return this.tabs[this.activeTab].component
}
}
}
</script>
```
2. 在每个 tab 内容组件中添加一个 `activated` 方法,该方法会在组件被加载时被调用:
```
<template>
<div>
<!-- tab 内容 -->
</div>
</template>
<script>
export default {
activated() {
// 在这里实现 tab 内容的刷新逻辑
}
}
</script>
```
3. 在父组件中,监听 `activeTab` 的变化,在变化时调用当前 tab 内容组件的 `activated` 方法:
```
<template>
<div>
<div class="tab" v-for="(tab, index) in tabs" :key="index" @click="activeTab = index">{{ tab.title }}</div>
<component :is="currentTabComponent"></component>
</div>
</template>
<script>
import Tab1 from './Tab1.vue'
import Tab2 from './Tab2.vue'
import Tab3 from './Tab3.vue'
export default {
components: {
Tab1,
Tab2,
Tab3
},
data() {
return {
tabs: [
{
title: 'Tab 1',
component: Tab1
},
{
title: 'Tab 2',
component: Tab2
},
{
title: 'Tab 3',
component: Tab3
}
],
activeTab: 0
}
},
watch: {
activeTab(newVal, oldVal) {
this.$children[oldVal].$options.activated = null
this.$children[newVal].$options.activated = () => {
this.$children[newVal].$forceUpdate()
}
}
},
computed: {
currentTabComponent() {
return this.tabs[this.activeTab].component
}
}
}
</script>
```
在上面的代码中,我们使用了 Vue 的 `watch` 方法监听 `activeTab` 的变化。在变化时,我们将当前 tab 内容组件的 `activated` 方法重写为一个新的方法,该方法会在组件被加载时强制刷新组件。这样,每次切换 tab 时,只会刷新当前 tab 内容组件,而不会影响其他 tab 内容组件的渲染。