Vue2 tab切換(選項卡)的一種寫法


  最近在學習Vue,看是案例后隨便做一個實踐,一遍加深理解;這種簡單又能實現效果的比較能夠接受;

html:結構很簡單:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>components</title>
    <script src="vue.js"></script>
    <style type="text/css">
        span{
            background:#ccc;
            padding:2px 5px;
            line-height:30px;
            text-align:center;
            cursor:pointer;
        }
        span.active{
            color:#fff;
            background:green;
        }
    </style>
</head>
<body>
    <div id="app">
        <component :is="who"></component>
        <span   :class="{active:active[key]}"   v-for="(item,key) in tab" @click="change(key)">{{item.content}} :{{key}}</span>
    </div>
</body>
</html>

js代碼:

<script type="text/javascript">
    var tem1 = {
        template: "<div>我是components_A組件</div>",
    };
    var tem2 = {
        template: "<div>我是components_B組件</div>",
    };
    var tem3 = {
        template: "<div>我是components_C組件</div>",
    };
    var vue1 = new Vue({
        el: "#app",
        data: {
            who: "com1",          //默認第一次顯示;
            active: [true, false, false],//統一管理狀態;
            tab: [{
                "content": "tab1",    //tab-span
                "func": "com1"           //僅僅用來存放組件;
            }, {
                "content": "tab2",
                "func": "com2"
            }, {
                "content": "tab3",
                "func": "com3"
            }]
        },
        updated: function() {
            // this.who=null;
        },

        methods: {
            change:function(x){
                
                for(var i=0;i<this.active.length;i++){
                    this.active[i]=false;
                    this.active[x]=true;
                    this.who=this.tab[x].func;
                }
                console.log(this.active);
                // console.log(x);
                this.$set(this.active, 3, 0);
            }
        },
        components: {
            "com1": tem1,
            "com2": tem2,
            "com3": tem3
        }
    })</script>

之前也是做了一個例子代碼比較凌亂,這個用v-for做簡化了;

要點之一: 不要忘記 v-for的遍歷順序  值-鍵;

要點之二: 關於全局API Vue.set();的使用;  應該在change方法中的循環之后用 this.$set調用;

      這里使用了一個小技巧就是關於active狀態的值在改變后如何更新呢,

      在其中后面加入一項,這一項並沒有什么意義,而僅僅是調用$set方法讓Vue知道;

要點之三: 關於component組件 is:who 如何引用到呢;把它發到被v-for遍歷的一個 func屬性中;這樣就方便了;

      事實上在data下再寫一個變量來存放 com1 com2 com3 是不會生效的;

 

以上完全是個人總結,純屬原創`,不足之處大家多多指教;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM