鍍金池/ 問答/HTML/ dom渲染元素復(fù)用的問題

dom渲染元素復(fù)用的問題

當(dāng)切換為 tab-2 時候,將其color設(shè)置為red
再切換回 tab-1 時,color的值并未消失
代碼如下:也可以點擊這里查看

<div id="app">
    <ul>
        <li :class="`tab${item}`"
            v-for="item in tabs"
            v-if="tabIndex === item">tab-{{item}}</li>
    </ul>
    <button @click="switchTab">switch</button>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            tabs: [1, 2],
            tabIndex: 1
        },
        methods: {
            switchTab () {
                this.tabIndex = this.tabIndex === 1 ? 2 : 1
                this.$nextTick(() => {
                    if (this.tabIndex === 2) {
                        document.querySelector('.tab2').style.color = 'red'
                    }
                })
            }
        }
    })
</script>
回答
編輯回答
野橘

vue在很多情況下 特別是循環(huán) 會原地復(fù)用dom
你不信可以在控制臺試驗一下

clipboard.png

既然是同一個dom 你只給他變紅又沒給他變回來 自然是紅色的。

解決方案很多,隨便挑一個

  1. v-for的時候加個:key 使得不要原地復(fù)用
  2. 不要使用dom操作了。data里放個變量isRed = false 然后對應(yīng)一個css叫red 然后<li :class={red:isRed}>...</li>
  3. v-if改v-show

另外,這數(shù)據(jù)的結(jié)構(gòu)其實不大合理。。
再另外,this.tabIndex = this.tabIndex === 1 ? 2 : 1這段不大好,也要考慮到以后有n(n>2)個標簽,不要寫這么死 寫活一點

2017年8月14日 23:19