V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yuann72
V2EX  ›  问与答

vue2 中 v-for 不能嵌套使用 v-if 吗?

  •  
  •   yuann72 · 2017-08-29 14:00:36 +08:00 · 4174 次点击
    这是一个创建于 2433 天前的主题,其中的信息可能已经有所发展或是发生改变。

    v-for 中嵌套使用 v-if 报错
    是我哪里写错了吗?

    <body>
        <div id="test">
            <p v-for="d in hhh">
                {{  d  }}
                {{  d.type  }}
                {{  d.msg  }}
                <h1 v-if="   d.type == 'h1'   "> {{ d.msg }} </h1>
                <h2 v-if="   d.type == 'h2'   "> {{ d.msg }} </h2>
                <h3 v-if="   d.type == 'h3'   "> {{ d.msg }} </h3>
            </p>
        </div>
    </body>
    <script src="../vue.js"></script>
    <script >
       let vm= new Vue({
            el:"#test",
            data:{
                hhh:[
                    {
                        'type':'h1',
                        'msg':'h1h1h1'
                    },
                    {
                        'type':'h2',
                        'msg':'h2h2h2'
                    },
                    {
                        'type':'h3',
                        'msg':'h3h3h3'
                    },
                ]
            },
        });
    </script>
    

    下面是浏览器的报错信息:

    [Vue warn]: Property or method "d" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
    
    [Vue warn]: Error in render function: "TypeError: Cannot read property 'type' of undefined"
    
    4 条回复    2017-08-29 14:28:20 +08:00
    U2Fsd
        1
    U2Fsd  
       2017-08-29 14:17:34 +08:00   ❤️ 1
    xiaome
        2
    xiaome  
       2017-08-29 14:18:07 +08:00
    当它们处于同一节点,v-for 的优先级比 v-if 更高
    https://cn.vuejs.org/v2/guide/list.html#v-for-with-v-if
    yuann72
        3
    yuann72  
    OP
       2017-08-29 14:27:30 +08:00
    @xiaome v-for 和 v-if 并不是同级别啊, v-if 在 v-for 下一级
    yuann72
        4
    yuann72  
    OP
       2017-08-29 14:28:20 +08:00
    @U2Fsd 懂了,谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5719 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 60ms · UTC 01:50 · PVG 09:50 · LAX 18:50 · JFK 21:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.