一个简单的vuex应用的小例子,一段本身的学习记录。
todolist就是一个简单的输入框,一个按钮,一个文本显示区域,能够逐条进行删除。vue
1.在用vue-cli生成好的HelloWorld.vue文件中直接写代码,先删除全部的自带代码vuex
<template> <div class="hello"> <input type="text"> <button>增长事项</button> <ul> <li>item</li> </ul> </div> </template>
要把`input`中的值在通过`button`点击后,显示在`li`中,`input`有`v-model`属性进行值的绑定, 让`li`的数据是一个数组。至关于在数组中push input的值。
2.在src目录下,新建一个store文件夹,建立一个index.js文件vue-cli
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { inputVal: 'lily', list: ['1', '2', '3'] }, mutations: { changeListValue(state, inputVal) { state.list.push(inputVal) state.inputVal = '' }, handleDel(state, idx) { state.list.splice(idx, 1) } }, actions: { changeListValue: ({commit}, inputVal) => { return commit('changeListValue', inputVal) }, handleDel: ({commit}, idx) => { return commit('handleDel', idx) } } }) export default store
3.回到HelloWorld.vue数组
<template> <div class="hello"> <input v-model="$store.state.inputVal" type="text"> <button @click="changeListValue(inputVal)">增长事项</button> <ul v-for="(item, idx) in list"> <li @click="handleDel(idx)">{{item}}</li> </ul> </div> </template> <script> import {mapState, mapActions} from 'vuex' export default { name: 'HelloWorld', computed: { ...mapState(['list', 'inputVal']) }, methods: { ...mapActions(['changeListValue', 'handleDel']) } } </script>
4.完成之后,有个困扰就是在input
的v-model
中写inputVal
会报错,请大神帮我解答下。学习