首页 > 解决方案 > 更新Vue组件数据中的数组

问题描述

我的组件数据中有一个键,它可能被初始化为 null 或里面有一些字符串。我希望能够创建尽可能多的关联键,同时还允许将其初始化为 null 或具有多个值。我遇到的问题是,每次我按下按钮添加一个新的输入字段时,页面都会重新呈现,然后数据会在再次初始化后重置。

我一直在看这篇文章,我在 addKeys 函数中放置了一个调试器,并收到错误消息this.licence.associatedKeys.$set is not a function。我不明白这个错误,也不确定如何将元素添加到 associatedKeys 数组

<template>
    <div>
        <form>
            <label>Associated Keys</label>
            <button v-on:click="addNewKey">Add new key</button>
            <div v-for="(k,index) in licence.associatedKeys" :key="k">
                <input type="text" :value="k" @input="licence.associatedKeys[index]=$event.target.value">
            </div>  
        </form>
    </div>
</template>

<script>
import util from '~/assets/js/util'
export default {
    methods: {
        addNewKey() { 
            this.licence.associatedKeys.$set(this.licence.associatedKeys, null)
        }
    },
    data: () => ({
        licence: {
            associatedKeys: []
        }
    })
}
</script>

标签: javascriptvue.jsvuex

解决方案


看看事件修饰符,特别是这个例子:

<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>

我认为这是您停止页面重新加载所需要的。

至于未定义的错误:您可以尝试使用实例本身,即

this.$set('license.associatedKeys[' + this.license.associatedKeys.length + ']', null); 

此外,您可能误读了文档,嵌套数据属性的.$setand.$add方法采用参数。所以,你应该写

this.licence.associatedKeys.$set(this.licence.associatedKeys.length, null)

推荐阅读