vue动态改变对象或者数组
从Vue官网上了解到,受现代js的限制,Vue无法检测到对象属性的添加或删除,那么我们可以通过以下几种方式去添加对象或者数组的属性:
改变对象属性
可以使用全局 Vue.set(this.someObj, key, value) 方法向嵌套对象添加响应式属性
可以使用 this.$set(this.someObj, key, value) ,这是全局Vue.set方法的别名
可以使用 this.someObj = Object.assign({}, this.someObj, {key:value}) (不了解Object.assign()方法的建议先看MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign )
最后举个栗子:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{JSON.stringify(obj)}}</h2>
</template>
<script>
import Vue from "vue";
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome to Your Vue.js App",
obj: {
mounted() {
Vue.set(this.obj, "b", 2);
this.$set(this.obj, "c", 3);
this.obj = Object.assign({}, this.obj, { d: 4 });
</script>
//页面上看到的结果是{"a":1,"b":2,"c":3,"d":4}
以上方法都要注意对象不能是 Vue 实例(在组件中Vue实例指的就是this),或者 Vue 实例的根数据对象(在组件中指的就是根组件里为对象时候的data)。
当你利用索引直接设置一个数组项时,例如:this.arr[index] = newValue;当你修改数组的长度时,例如:this.arr.length = newLength,Vue不能检测到该数组的变动,我们可以利用以下方法触发更新:
会改变原数组的一些方法,Vue也能观察到数组的变化触发视图更新,这些方法如下:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
重新赋值数组,像filter(), concat(), slice()这些方法不会改变原数组,但总是返回一个新数组,那么我们可以利用新数组替换旧数组,如下代码:
this.arr = this.arr.filter((item,index)=>{
return item.id != 1
可以通过Vue.set(this.arr, index, newValue)方法改变数组的值
可以通过this.arr.splice(index, 1, newValue)方法改变数组的值,不了解splice()方法的可以自行参考MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
如果你想修改数组长度,可以通过this.arr.splice(newLength)方法实现
讲一个实际项目中我们容易遇上的栗子,比如一个列表,我们需要点击一个按钮后改变某一列的状态以此来做一些判断,那么我们可以如下实现:
handleClick(index){
this.arr.splice(index,1,{
...this.arr[index],
flag:true //相当于新增一个标记方便对某一列进行一些逻辑判断
参考vue官网列表渲染:https://cn.vuejs.org/v2/guide/list.html
参考vue官网深入响应式原理:https://cn.vuejs.org/v2/guide/reactivity.html
react动态改变对象或者数组
修改对象中的某项
this.setState({
obj: {
...obj,
key: value
updateArray(index, key, value){
const clone = this.state.arr.slice();
clone[index][key] = value;
this.setState({
arr: clone
//法二 //不推荐,官方提醒,应该把this.state当成不可变变量
updateArray(index, key, value){
let { arr } = this.state
arr[index][key] = value;
this.setState({
updateArray(index, key, value){
this.setState({
arr: this.state.arr.map((item, _index) =>
_index === index ? { ...item, [key]: value } : item