功能需求
- 展示一個表格,表格包含選項有“ 姓名 年齡 是否顯示”三個列表項
- 是否顯示列表項是可操作開關,點擊切換打開/關閉
- 將表格中開關為打開狀態的列表項,在另一個表格中顯示
需求分析
根據功能需求,
- 我們需要定義兩個頁面組件: 用作渲染所有數據的組件,新建allList.vue文件; 用作渲染選中數據的組件,新建filterList.vue文件
- 我們可以使用vuex狀態管理,引入vuex跟蹤數據狀態變化
- 定義數據結構,做列表渲染用
目錄結構
下面該demo的目錄結構
代碼編寫
狀態管理文件
首先定義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父容器組件
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>
子組件AllData
computed計算屬性中返回store中的列表數據todoList,切換開關出發switchChange方法提交store中mutation更改todoList數據
<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>
FilterData子組件
這個組件中只做過濾數據渲染,在computed計算屬性中返回store的getters中的數據。getters在vuex中相當於vue的computed計算屬性,返回過濾后的數據。
<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>
以上~