javascript - 更新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>
解决方案
看看事件修饰符,特别是这个例子:
<!-- 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);
此外,您可能误读了文档,嵌套数据属性的.$set
and.$add
方法采用键和值参数。所以,你应该写
this.licence.associatedKeys.$set(this.licence.associatedKeys.length, null)
推荐阅读
- php - 使用大关联数组更新记录而不是插入
- php - laravel 6 中的数据屏蔽
- python - 根据字段值更改嵌套序列化程序
- mapbox - 让 followWithHeading 更准确
- neo4j - Neo4J 保存查询性能(GrapheneDB)
- asp.net-mvc - ASP.NET MVC & MEF - 可插拔架构
- python - 使用聚合管道运算符和 python 代码创建 MongoDB 视图
- ironpython - IronPython 中“sizeof”运算符的替代方案是什么?
- python - 如何使用计算字段创建弹出向导?
- c# - 如何将具有多个值的 URL 解析为多个 int