Vuex(三)
- 使用Vuex写一个todos案例
第一步:创建项目
打开powerShell管理员控制面板输入vue ui进入可视化面板创建vue项目
第二步:正常创建项目,安装项目依赖包 axios、vuex、ant-design-vue
注意:因为项目中使用了eslint,所以要注意代码格式化
app.vue中的代码
<template>
<div id="app">
<a-input
placeholder="请输入任务"
class="my_ipt"
:value="inputValue"
@change="handleInputChange"
/>
<a-button type="primary" @click="addItemToList">添加事项</a-button>
<!-- 这里要把list改为infolist -->
<a-list bordered :dataSource="infolist" class="dt_list">
<a-list-item slot="renderItem" slot-scope="item">
<!-- 复选框 通过:checked属性为选项动态绑定done状态 声明change事件改变复选框的状态-->
<a-checkbox
:checked="item.done"
@change="
e => {
cbStatusChanged(e, item.id)
}
"
>{{ item.info }}</a-checkbox
>
<!-- 删除链接 -->
<a slot="actions" @click="removeItemById(item.id)">删除</a>
</a-list-item>
<!-- footer区域 -->
<div slot="footer" class="footer">
<!-- 未完成的任务个数 使用插值表达式渲染-->
<span>{{ unDoneLength }}条剩余</span>
<!-- 操作按钮 通过三元表达式来判断选中的按钮从而设置为primary状态-->
<a-button-group>
<a-button
:type="viewKey === 'all' ? 'primary' : 'default'"
@click="changeList('all')"
>全部</a-button
>
<a-button
:type="viewKey === 'unDone' ? 'primary' : 'default'"
@click="changeList('unDone')"
>未完成</a-button
>
<a-button
:type="viewKey === 'done' ? 'primary' : 'default'"
@click="changeList('done')"
>已完成</a-button
>
</a-button-group>
<!-- 把已经完成的任务清空 -->
<a @click="clean">清除已完成</a>
</div>
</a-list>
</div>
</template>
<script>
// 按需导入
import { mapState, mapGetters } from 'vuex'
export default {
name: 'app',
data() {
return {}
},
// 声明一个生命周期函数 diapatch是调用actions函数中getList的方法
created() {
this.$store.dispatch('getList')
},
// 声明一个计算属性
computed: {
// 这里要把list改成infolist并且放入下面
...mapState(['inputValue', 'viewKey']),
// 未完成
...mapGetters(['unDoneLength', 'infolist'])
},
// 声明要绑定的方法
methods: {
// 监听文本框内容变化 只要发生变化就会拿到事件参数e
handleInputChange(e) {
// e.target.value拿到当前文本框最新的值
console.log(e.target.value)
// this.$store.commit获取/调用mutations中的setInputValue方法,把具体的参数传进去
this.$store.commit('setInputValue', e.target.value)
},
// 向列表中新增项
addItemToList() {
// 使用计算属性判断内容不能为空 如果为空就跳出警告弹窗
if (this.inputValue.trim().length <= 0) {
return this.$message.warning('文本框内容不能为空!')
}
// 通过this.$store.commit调用Mutations里的addItem函数
this.$store.commit('addItem')
},
// 根据id删除列表对应的事项
removeItemById(id) {
// console.log(id)
// 通过this.$store.commit调用matations中removeItem函数删除id对应的事项
this.$store.commit('removeItem', id)
},
// 监听复选框 选中状态变化的事件
cbStatusChanged(e, id) {
// 通过e.target.checked获取最新的选中状态
// console.log(e.target.checked)
// console.log(id)
// 创建param参数对象
const param = {
id: id,
status: e.target.checked
}
// 调用mutations中的changeStatus函数
this.$store.commit('changeStatus', param)
},
// 清楚已完成的任务
clean() {
// 调用mutations中的cleanDone函数,清除已完成的事项
this.$store.commit('cleanDone')
},
// 修改页面上展示列表的数据
changeList(key) {
console.log(key)
// 调用mutations中的函数
this.$store.commit('changeViewKey', key)
}
}
}
</script>
<style scoped>
#app {
padding: 10px;
}
.my_ipt {
width: 500px;
margin-right: 10px;
}
.dt_list {
width: 500px;
margin-top: 10px;
}
.footer {
display: flex;
justify-content: space-between;
align-items: center;
}
</style>
index.js中的代码
/*
* @Descripttion:
* @version:
* @Author: 会飞的猪礼
* @Date: 2021-09-04 09:16:51
* @LastEditors: 会飞的猪礼
* @LastEditTime: 2021-09-04 21:10:43
*/
import Vue from 'vue'
import Vuex from 'vuex'
// axios异步请求 放入到actions中 异步处理数据
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// 所有的任务列表
list: [],
// 文本框的内容
inputValue: 'aaa',
// 下一个ID
nextId: 5,
// 默认展示所有的数据
viewKey: 'all'
},
mutations: {
// mutations中的第一个参数都是state 接收一个list参数进来
initList(state, list) {
// 把list赋值到state中的list里去
state.list = list
},
// 定义一个获取新值的方法 第一个参数永远是state 第二个是传入的新值
// 为store(state)中的inputValue赋值
setInputValue(state, val) {
// 将传入的新值给inputValue
state.inputValue = val
},
// 添加列表项目
addItem(state) {
const obj = {
id: state.nextId,
info: state.inputValue.trim(),
done: false
}
// 把obj对象增加到list列表当中
state.list.push(obj)
// 让每一个id自增加一
state.nextId++
// 添加事项完成后 将inputValue清空
state.inputValue = ''
},
// 根据id删除对应的事项
removeItem(state, id) {
// 根据id查找对应项的索引
const i = state.list.findIndex(x => x.id === id)
// 根据索引 删除对应的元素
if (i !== -1) {
state.list.splice(i, 1)
}
},
// 修改列表项的选中状态
changeStatus(state, param) {
const i = state.list.findIndex(x => x.id === param.id)
if (i !== -1) {
state.list[i].done = param.status
}
},
// 清除已完成的事项
cleanDone(state) {
// 将未完成的事项过滤出来,重新赋值给state中的list
state.list = state.list.filter(x => x.done === false)
},
// 修改视图的关键字
changeViewKey(state, key) {
state.viewKey = key
}
},
actions: {
// 声明一个异步函数请求数据
getList(context) {
axios.get('/list.json').then(({ data }) => {
console.log(data)
// commit是触发mutations中函数的方法 此时data就是所获取的真实数据
context.commit('initList', data)
})
}
},
// 对数据包装
getters: {
// 统计未完成的任务条数
unDoneLength(state) {
// x代表每一项 x.done为false就满足过滤器的条件 返回一个新的数组长度
return state.list.filter(x => x.done === false).length
},
// 点击对应的按钮显示对应的内容
infolist(state) {
// 如果点击全部按钮则显示全部的事项
if (state.viewKey === 'all') {
return state.list
}
// 如果点击的是未完成按钮则显示未完成的内容
if (state.viewKey === 'unDone') {
return state.list.filter(x => !x.done)
}
// 如果点击的是已完成按钮则显示已完成的内容
if (state.viewKey === 'done') {
return state.list.filter(x => x.done)
}
return state.list
}
}
})
list.json中的代码
[
{
"id": 0,
"info": "Racing car sprays burning fuel into crowd.",
"done": true
},
{ "id": 1, "info": "Japanese princess to wed commoner.", "done": false },
{
"id": 2,
"info": "Australian walks 100km after outback crash.",
"done": true
},
{ "id": 3, "info": "Man charged over missing wedding girl.", "done": false },
{ "id": 4, "info": "Los Angeles battles huge wildfires.", "done": false }
]
.eslintrc.js中的代码
/*
* @Descripttion:
* @version:
* @Author: 会飞的猪礼
* @Date: 2021-09-04 09:16:51
* @LastEditors: 会飞的猪礼
* @LastEditTime: 2021-09-04 10:56:48
*/
module.exports = {
root: true,
env: {
node: true
},
extends: ['plugin:vue/essential', '@vue/standard'],
parserOptions: {
parser: 'babel-eslint'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
// 严格的语言错误,需要有空格,但是在这把它设置为0
'space-before-function-paren': 0
}
}
.prettierrc中的代码 { "semi": false, "singleQuote": true }
案例结果展示
添加

删除

未完成

已完成

清除


浙公网安备 33010602011771号