鍍金池/ 問答/PHP  數(shù)據(jù)庫(kù)  HTML/ 關(guān)于vue.js中v-if條件不可以實(shí)時(shí)隨之改變的問題

關(guān)于vue.js中v-if條件不可以實(shí)時(shí)隨之改變的問題

為什么在點(diǎn)擊菜單欄的時(shí)候activeIndex的值更新了,但是v-if的條件卻沒有生效呢?

<template lang="html">
<div>
    <div class="child-page-toolbar">
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
            <el-menu-item index="1">
                <a>菜單一</a>
            </el-menu-item>
            <el-menu-item index="2">
                <a>菜單二</a>
            </el-menu-item>
            <el-menu-item index="3">
                <a>菜單三</a>
            </el-menu-item>
            <el-menu-item index="4">
                <a>菜單四</a>
            </el-menu-item>
        </el-menu>
    </div>

    <span v-if="activeIndex === '1'"></span>

    <span v-else-if="activeIndex === '2'">這是2</span>

</div>

</template>
<script>
    export default {
        data() {
            return {
                activeIndex: '2'
            }
        },
        methods: {
            handleSelect(activeIndex, keyPath) {
                if (activeIndex === '1') {
                    console.log(activeIndex);
                }else if (activeIndex === '2') {
                    console.log(activeIndex);
                }
            }
        }
    }
</script>

clipboard.png

回答
編輯回答
悶油瓶

activeIndex 這個(gè)還是2啊。你只是判斷了,沒有改變它。
所以顯示這是2是對(duì)的啊。

<el-menu-item index="1">
    <a>菜單一</a>
</el-menu-item>
<el-menu-item index="2">
    <a>菜單二</a>
</el-menu-item>
<el-menu-item index="3">
    <a>菜單三</a>
</el-menu-item>
<el-menu-item index="4">
    <a>菜單四</a>
</el-menu-item>
// 上面代碼可以用v-for優(yōu)化下
let menuArr = ['一', '二', '三', '四']
<el-menu-item v-for="(item, index) in menuArr" :index="index+1">
    <a>菜單{{menuArr[index]}}</a>
</el-menu-item>
handleSelect(activeIndex, keyPath) {
    this.activeIndex = activeIndex;
    console.log(this.activeIndex);
    // if (activeIndex === '1') {
    //    console.log(activeIndex);
    // }else if (activeIndex === '2') {
    //    console.log(activeIndex);
    //}
}
2017年2月26日 15:08
編輯回答
糖果果

試試采用計(jì)算屬性呢

2017年8月20日 18:17
編輯回答
別瞎鬧
handleSelect(activeIndex, keyPath) {
    this.activeIndex = activeIndex;
    if (activeIndex === '1') {
        console.log(activeIndex);
    }else if (activeIndex === '2') {
        console.log(activeIndex);
    }
}
2017年2月9日 08:53