vue中的选项卡

对于选项卡来说,最大的问题是切换选项卡,

如果在一个文件内,设置一个变量就可以解决一切了,

<template>
  <div>
    <div class="tab">
      <div @click="toggle(1)" :class="{active:index === 1}">
        <span>tab1</span>
      </div>
      <div @click="toggle(2)" :class="{active:index === 2}">
        <span>tab2</span>
      </div>
    </div>
    <div v-show="index === 1"> container1</div>
    <div v-show="index === 2"> container2</div>
  </div>
</template>
<script>
export default {
  name: "Test",
  data() {
    return {
      index:0
    }
  },
  methods:{
    toggle(id){
      if(id === this.index){
        this.index = 0;
      }else{
        this.index = id;
      }
    }
  }
};
</script>
<style scoped>
.tab{
  display: flex
}
.tab div{
  margin: 10px;
  padding: 10px;
  border: 1px solid #ababab;
  border-radius: 7px;
}
.active{
  background: red;
  color: #fff;
}
</style>


如果写的子组件,可以使用vuex解决这个问题,vuex是一个专为 Vue.js 应用程序开发的状态管理模式,

首先引入vuex

import vuex from 'vuex'
Vue.use(vuex);
const store = new vuex.Store({//store对象
    state:{
        status:0
    },
    mutations:{
      show(state,num){
        state.status=num;
      }
    }
})

然后在组件中的计算属性中返回状态

computed: {
    status () {
      return  this.$store.state.status
    }
  }

这个staus就是一个响应式的全局状态,在任何一个子组件中都可以使用并且改变他

toggle() { 
      if(this.status === 3){
        this.$store.commit('show', 0);
      }else{
        this.$store.commit('show', 3);
      }
    },

猜你喜欢

转载自blog.csdn.net/Y17868877685/article/details/88550204