本节完成任务的新增:点击添加事项完成 inputValue 到 list 的添加。
视频地址:https://www.bilibili.com/video/BV1h7411N7bg?p=17
注意点:
1、 list每个item都包含id、info、done。id是需要自增的,这节实现思路很巧妙。
2、完成新增之后记得清空输入框内容。
3、保存输入框内容到任务项时,使用trim剔除前后空格+判空处理。
1、store/index.js——增加变量nextId,增加 addInputValue 方法存储输入框内容到列表中。
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
list: [],
inputValue: '', // 文本框内容
nextId: 5 // list中id属性取值
},
mutations: {
initList (state, step) {
state.list = step
},
// 为 inputValue 赋值
setInputValue (state, val) {
state.inputValue = val
},
// 将inputValue存储到list中
addInputValue (state) {
const obj = {
id: state.nextId,
info: state.inputValue.trim(),
done: false
}
state.list.push(obj)
state.nextId++
state.inputValue = ''
}
},
actions: {
getList (context) {
axios.get('/list.json').then(({ data }) => {
console.log(data)
context.commit('initList', data)
})
}
}
})
2、App.vue——添加按钮绑定addItemToList(),触发存储事件
<template>
<div id="app">
<a-input
placeholder="请输入任务"
class="my_ipt"
:value="inputValue"
@change="handleInputChange"
/>
<a-button type="primary" @click="addItemToList()">添加事项</a-button>
<a-list bordered :dataSource="list" class="dt_list">
<a-list-item slot="renderItem" slot-scope="item">
<!-- 复选框 -->
<a-checkbox>{{ item.info }}</a-checkbox>
<!-- 删除链接 -->
<a slot="actions">删除</a>
</a-list-item>
<!-- footer区域 -->
<div slot="footer" class="footer">
<!-- 未完成的任务个数 -->
<span>0条剩余</span>
<!-- 操作按钮 -->
<a-button-group>
<a-button type="primary">全部</a-button>
<a-button>未完成</a-button>
<a-button>已完成</a-button>
</a-button-group>
<!-- 把已经完成的任务清空 -->
<a>清除已完成</a>
</div>
</a-list>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
name: 'app',
data () {
return {}
},
created () {
this.$store.dispatch('getList')
},
computed: {
...mapState(['list', 'inputValue'])
},
methods: {
...mapMutations(['setInputValue', 'addInputValue', 'removeItem']),
// 监听文本框内容变化
handleInputChange (e) {
// 拿到最新值,并同步到store
console.log(e.target.value)
this.setInputValue(e.target.value)
},
// 向列表项中新增 item 项
addItemToList () {
if (this.inputValue.trim().length <= 0) { // 判空处理
return this.$message.warning('文本框内容不能为空')
}
this.addInputValue()
}
}
}
</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>