关于vue.js中v-if条件不可以实时随之改变的问题

为什么在点击菜单栏的时候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

阅读 9k
3 个回答
handleSelect(activeIndex, keyPath) {
    this.activeIndex = activeIndex;
    if (activeIndex === '1') {
        console.log(activeIndex);
    }else if (activeIndex === '2') {
        console.log(activeIndex);
    }
}

试试采用计算属性呢

activeIndex 这个还是2啊。你只是判断了,没有改变它。
所以显示这是2是对的啊。

<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优化下
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);
    //}
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题