博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
VUE计算属性computed的get和set / 过滤 /存储数据
阅读量:774 次
发布时间:2019-03-24

本文共 1440 字,大约阅读时间需要 4 分钟。

一、computed计算属性

get是其他的数据来获取computed里定义的那个数据,决定返回值。

set是根据computed里定义的那个数据值来改变其他的数据。

computed:{
checkAllBox:{
get(){
return this.listsSize===this.lists.length && this.listsSize>0; }, set(value){
this.checkList(value); } }},

get函数是checkAllBox选框来获取get函数的返回值。

set函数是调用checkList来改变其他的值,形参是value表示选框是否被选中的状态。

二、过滤数组,删除选中的数据

删除被选中的数据:

data(){
return{
lists:[{
title:'一',complain:false}, {
title:'二',complain:false}, {
title:'三',complain:true} ] } }, //删除的方法 deleteComplain(){
//定义过滤器,过滤掉complain为false的 //删除状态为true选中的数据 this.lists=this.lists.filter(list => list.complain===false); },//在todoFooter 组件中调用该方法 this.deleteComplain();

三、计算被选中的数量

通过数组的reduce()方法。

listsSize(){
//判断lists中状态是true的,然后数量叠加起来 return this.lists.reduce((preTotal,lists) => preTotal+(lists.complain?1:0),0); },

preTotal初始值为0,如果lists.complain为true,则preTotal+1,否则+0。

四、存储数据localStorage

1.读取本地储存:window.localStorage.getItem('todos_key')

2.运用JSON.parse转换为JsonObject

JSON.parse(localStorage.getItem('todos_key') || '[]')存储为null的话就读取[]

3.深度监视

watch:{
//监视 lists:{
deep:true,//深度监视 handler:function(value){
//value就是lists //将lists最新的值的json数据,保存到localStorage window.localStorage.setItem('todos_key',JSON.stringify(value)) } } },

转载地址:http://hsrkk.baihongyu.com/

你可能感兴趣的文章