The problem of reuse of dom rendering elements

when you switch to tab-2 and set its color to red
and then switch back to tab-1, the value of color does not disappear
code is as follows: you can also click here to view

.
<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: "-sharpapp",
        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>
Mar.18,2021

vue in many cases, especially loops, will reuse dom in place
you can try it on the console

clipboard.png

since it is the same dom, you only make it red but not change it back, it is naturally red.

there are many solutions, just pick one

    When
  1. v-for, add: key so that do not reuse in place
  2. Don't use the dom operation. Put a variable isRed = false in data and then correspond to a css called red and then < li: class= {red:isRed} >.
  3. v-if change to v-show

in addition, the structure of this data is not reasonable. No, no, no.
in addition, the paragraph this.tabIndex = this.tabIndex = 1? 2: 1 is not good. Consider that there will be a n (n > 2) tag in the future. Don't write so dead and live

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b38472-2c0e6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b38472-2c0e6.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?