根据功能需求,vue
下面该demo的目录结构
vuex
首先定义todoList变量,存放列表数据。当localStorage中没有todolist时,就将列表数组给到todoList变量,不然就从localStorage中取值。这样作的目的是,当咱们操做了列表,防止刷新时列表状态又回复到最原始的状态。 使用本地存储保证刷新后状态也是最后一次操做的状态。数组
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); var todoList = JSON.parse(localStorage.getItem('todolist')) || [ {id:1,name:'赵一铭',age:26,level:9,isShow:true}, {id:2,name:'钱二婷',age:19,level:1,isShow:true}, {id:3,name:'孙三堤',age:22,level:7,isShow:false}, {id:4,name:'李四喜',age:23,level:3,isShow:true}, {id:5,name:'周六冉',age:24,level:4,isShow:false} ]; const store = new Vuex.Store({ state:{ todoList:todoList }, mutations:{ changeTodoList(state,row){ state.todoList.find((item,index) => { if(item.id == row.id){ item.isShow = row.isShow } }) localStorage.setItem('todolist',JSON.stringify(state.todoList)) } }, getters:{ todoList:state => { return state.todoList.filter(todo => todo.isShow) } } }) export default store;
App.vue文件咱们只当作父容器组件,在如组件中引入两个子组件AllData
、FilterData
数据结构
<template> <div id="app"> <h1>List Demo</h1> <div class="content"> <div class="item"> <all-data></all-data> </div> <div class="item"> <filter-data></filter-data> </div> </div> </div> </template> <script> import AllData from './components/allList'; import FilterData from './components/filterList' export default { name:'App', components:{ AllData, FilterData } } </script>
computed计算属性中返回store中的列表数据todoList,切换开关出发switchChange方法提交store中mutation更改todoList数据app
<template> <div> <template> <el-table :data="todoList" border style="width=100%"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> <el-table-column label="是否显示"> <template slot-scope="scope"> <el-switch v-model="scope.row.isShow" active-color="#13ce66" inactive-color="#ccc" @change="switchChange(scope.row)"></el-switch> </template> </el-table-column> </el-table> </template> </div> </template> <script> export default { computed:{ todoList(){ return this.$store.state.todoList } }, methods:{ switchChange(row){ this.$store.commit('changeTodoList',row) } } } </script>
这个组件中只作过滤数据渲染,在computed计算属性中返回store的getters中的数据。getters在vuex中至关于vue的computed计算属性,返回过滤后的数据。this
<template> <div> <template> <el-table :data="todos" border style="width=100%"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> </el-table> </template> </div> </template> <script> export default { computed:{ todos(){ return this.$store.getters.todoList } }, methods:{ } } </script>
以上~code