根據功能需求,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