首页 > 编程 > JavaScript > 正文

详解vuex的简单todolist例子

2019-11-19 11:11:11
字体:
来源:转载
供稿:网友

一个简单的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会报错,请大神帮我解答下。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表