这节主要实现文本框内容双向同步,输入框 <——>公共数据store。
强烈建议自己敲一遍代码,有很多不经意的细节问题会导致各种error。
视频地址:https://www.bilibili.com/video/BV1h7411N7bg?p=16
完整代码仓库地址:https://github.com/huijieya/vuex_demo
1、 store/index.js——增加变量inputValue用来实时存储文本框内容,setInputValue为其赋值。
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
list: [],
inputValue: '' // 文本框内容
},
mutations: {
initList (state, step) {
state.list = step
},
// 为 inputValue 赋值
setInputValue (state, val) {
state.inputValue = val
}
},
actions: {
getList (context) {
axios.get('/list.json').then(({ data }) => {
console.log(data)
context.commit('initList', data)
})
}
}
})
2、App.vue—— mapState实现store到文本框的同步,文本框绑定@change实现从文本框到store的同步。
注意:
- :value而不是v-model;
- @change="handleInputChange而不是@change=“handleInputChange()”;
- 改变store的变量用mutation;
<template>
<div id="app">
<!-- 绑定inputValue,添加change事件 -->
<a-input placeholder="请输入任务" class="my_ipt" :value="inputValue" @change="handleInputChange"/>
<a-button type="primary">添加事项</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: {
// 将mutations映射为methods
...mapMutations(['setInputValue']),
// 监听文本框内容变化, 拿到最新值,并同步到store
handleInputChange (e) {
console.log(e.target.value)
this.setInputValue(e.target.value)
}
}
}
</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>