vue 将属性变成响应式方案

数组:
	当数组元素的改变数组长度改变不能触发状态更新		
		arr[n]='x';	但如果元素是一个对象(非数组),修改是响应式的
		arr.length=n;
	
	解决方法:
		第一种:Vue.set(数组对象,索引,值);	或this.$set(...)
		第二种:调用splice方法
	

对象:
	(1)当添加和删除属性时,新的属性和删除的属性不是响应式的
	
		解决方法:
			Vue.set(对象名,'属性',属性的值);  设置一次后,该属性就会被vue数据绑定
			
	(2)为已有对象赋值多个新属性
		Object.assign(this.someObject, { a: 1, b: 2 })	此种方式不会将新属性变成响应式,因为并没有调用someObject对象的set和get方法
		
		解决方法:
			this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })	
				重新赋值给someObject,会触发someObject的set方法,将新赋值的数据变成响应式的

响应式删除
	Vue.delete(target,属性名/索引)
	this.$delete(target,属性名/索引)

代码示例:

 if(food.count)
 {
   food.count++;

 }else{

    Vue.set(food,'count',1); //让对象新增的数据能够被vue数据绑定,动态更新
 }

<template>
  <div id="app">
    <div>
      <input type="text"/>
      <ul>
        <li v-for='(item,index) in arr' :key='index' @click="clc(index)">
          <input type='checkbox' :checked='arr[index]'> 
          <!-- item.done -->
          内容+{{index}}
        </li>
        <button class='b' @click='c1'>全部</button>
        <button class='b' @click='c2'>未完成</button>
        <button class='b' @click='c3'>已完成</button>
      </ul>
    </div>
    <div class='btn'>
      <button>提交</button>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  data(){
    return{
      // arr:[{done:false},{done:false},{done:false},{done:false},{done:false}],
      arr:[false,false,false,false,false],
      index2:0,
      flag:false
    }
  },
  methods: {
    clc(index=0)
    {
      console.log(index);
      Vue.set(this.arr,index, !this.arr[index])
    }
  },
  
  components: {

  }
}
</script>

<style>
#app{
  display: flex;

}
#app>div{
  flex: 3;
  height: 30px;
  margin-right: 20px;
}
#app>div>input{
  height: 30px;
  width: 100%;
}
#app>div>ul>li{
  list-style: none;
  height: 30px;
  width: 100%;
  border: solid 1px #ccc;
  line-height: 30px;
}
.btn>button{
  flex:1;
  width: 120px;
  height: 40px;
  background-color:#0C8AFF;
  border: none;
  border-radius: 5px;
  color: white;
}
.b{
  width: 120px;
  height: 40px;
  background-color:#0C8AFF;
  border: none;
  border-radius: 5px;
  color: white;
  margin-right: 20px;
}

</style>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值