搜索

首页  >  问答  >  正文

javascript - v-for中无法获取push进来的数据?

下段代码中点击button后,app.items2数组内容发生变化,第二个ul里也被渲染进一个li,但是items2内的item.message 缺没有渲染出来,请问是为什么,怎么解决?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>

    </style>
</head>
<body>
    <p id="example-1">
        <ul>
            <li v-for="item in items">
                {{ item.message }}
            </li>
            
        </ul>
        <ul>
            <li v-for="item in items2">{{ item.message }}</li>
        </ul>
        <button @click="aaa">移动</button>
    </p>
    <script src="http://vuejs.org/js/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#example-1',
            data: {
                items: [{
                    message: 'Foo'
                }, {
                    message: 'Bar'
                }],
                items2: []
            },
            methods: {
                aaa: function() {
                    this.items2.push(this.items.splice(0, 1));
                }
            }
        })
    </script>
</body>
</html>
PHPzPHPz2832 天前797

全部回复(3)我来回复

  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:23:07

    Array.prototype.splice() 返回值 由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。

    https://developer.mozilla.org...

    this.items2.push(this.items.splice(0, 1)[0]);

    https://jsfiddle.net/ycloud/n...

    回复
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:23:07

    this.items2.push(...this.items.splice(0, 1));

    回复
    0
  • 黄舟

    黄舟2017-05-19 10:23:07

    splice方法返回一个数组
    push接受不定长参数
    可以使用concat方法
    this.items2 = this.items2.concat(this.items.splice(0, 1));

    回复
    0
  • 取消回复