首页 > 解决方案 > 模板中的 Vue.js 动态数组不起作用

问题描述

我刚开始摆弄 VueJs,我尝试了一个简单的例子,其中一个数组有值并在模板中使用它,它工作得很好

<body>
    <div id="app">
        {{operations.join(', ')}}
    </div>
</body>
<a href=""></a>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Understanding Hooks',
            operations: ['One', 'Two'],
        }
    })
</script>

但是,当我尝试动态填充操作(数组)时,页面/浏览器变得无响应(以下是代码)。任何输入都会有所帮助。

<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Undstanding Hooks',
            operations: ['One', 'Two'],
        },
        created: function() {
            console.log('=> ', this.operations)
            this.operations.push('CREATED : ');
        },
        mounted: function() {
            this.operations.push('MOUNTED : ');
        },
        updated: function() {
            this.operations.push('UPDATED : ');
        },
        destroyed: function() {
            this.operations.push('DESTROYED : ');
        },
    })
</script>

标签: javascriptvue.jsvuejs2

解决方案


更新

this.operations.push('UPDATED : ');将使组件updated挂钩无限运行。请尝试删除它。

还有一个关于 immutable 和 reactive 的最佳实践。的参考this.operations没有改变。

你应该使用

this.operations = [...this.operations, 'CREATED : ']

代替

this.operations.push('CREATED : ');

或者

this.operations = this.operations.concat(['CREATED :'])


推荐阅读