共计 1253 个字符,预计需要花费 4 分钟才能阅读完成。
一个简单的 vuex 应用的小例子,一段自己的学习记录。
todolist 就是一个简单的输入框,一个按钮,一个文本显示区域,可以逐条进行删除。
1. 在用 vue-cli 生成好的 HelloWorld.vue 文件中直接写代码,先删除所有的自带代码
<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 文件
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
会报错,请大神帮我解答下。
正文完