vue-array-and-object-update

by hysunny

HTML

<div id="app">
    <h3>1. 数组数据更新但是视图没有更新</h3>
    <ul>
        <li 
            v-for="(item, index) in list"
            @click="handleClick(index)"
        >
            <span>{{ item.name }}</span>
            <span>{{ clickedTimes[index]}}</span>
        </li>
    </ul>
    <h3>2. 数组数据更新,视图也更新</h3>
    <ul>
        <li 
            v-for="(item, index) in list"
            @click="handleClick1(index)"
        >
            <span>{{ item.name }}</span>
            <span>{{ clickedTimes[index]}}</span>
        </li>
    </ul>
    <h3>3. 对象数据更新但是视图没有更新</h3>
    <ul>
        <li 
            v-for="(value, key) in obj"
            @click="addPro(Number(key))"
        >
            <p>{{ value }}</p>
        </li>
    </ul>
    <h3>4. 对象数据更新,视图也更新</h3>
    <ul>
        <li 
            v-for="(value, key) in obj"
            @click="addPro1(Number(key))"
        >
            <p>{{ value }}</p>
        </li>
    </ul>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Vue

new Vue({
  el: "#app",
  data: {
    list: [
    	{ name: 'Jason' }, 
    	{ name: 'Cindy' },
        { name: 'Jay' }
    ],
    clickedTimes: [],
    obj: {
    	1: 0
    }
  },
  methods: {
  	handleClick(index){
    	if (!this.clickedTimes[index]) {
        	this.clickedTimes[index] = 1;
        } else {
        	this.clickedTimes[index] += 1;
        }
        console.log(this.clickedTimes[index])
    },
    handleClick1(index) {
    	if (!this.clickedTimes[index]) {
        	this.$set(this.clickedTimes, index, 1);
            // 异或 this.marked.splice(index, 1, 1) 
        } else {
        	this.$set(this.clickedTimes, index, this.clickedTimes[index] + 1);
        }
        console.log(this.clickedTimes[index])
    },
    addPro(key) {
    	this.obj[key + 1] = key;
        console.log(this.obj[key + 1] );
    },
    addPro1(key) {
    	this.$set(this.obj, key + 1, key)
        // 异或 this.obj = Object.assign({}, this.obj, { [key + 1]: key })
        console.log(this.obj[key + 1] );
    }
  }
})