<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/vue.js" ></script>
    </head>
    <body>
        <div id="box">
            <input type="button" value="添加" @click="add">
            <ul>
                <li v-for="val in arr">
                    {{val}}
                </li>
            </ul>
        </div>
    </body>
    <script>
        var vm = new Vue({
            data: {
                arr: ['apple','pear','orange']
            },
            methods:{
                add: function(){
                    //[Vue warn]: Duplicate value found in v-for="val in arr": "tomato". 
                    //Use track-by="$index" if you are expecting duplicate values.
                    //重复添加会报数据重复提示
                    this.arr.push('tomato');
                }
            }
        }).$mount('#box');
    </script>
</html>

当我们点击【添加】按钮两次之后,会出现如下报错信息
vue添加重复数据报错

使用track-by解决添加重复数据报错问题

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="js/vue.js" ></script>
    </head>
    <body>
        <div id="box">
            <input type="button" value="添加" @click="add">
            <ul>
                <li v-for="val in arr" track-by='$index'>
                    {{val}}
                </li>
            </ul>
        </div>
    </body>
    <script>
        var vm = new Vue({
            data: {
                arr: ['apple','pear','orange']
            },
            methods:{
                add: function(){
                    //[Vue warn]: Duplicate value found in v-for="val in arr": "tomato". 
                    //Use track-by="$index" if you are expecting duplicate values.
                    //重复添加会报数据重复提示
                    this.arr.push('tomato');
                }
            }
        }).$mount('#box');
    </script>
</html>

解决vue添加相同数据报错

Logo

前往低代码交流专区

更多推荐