vuex的簡單todolist例子

一個簡單的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.完成之後,有個困擾就是在inputv-model中寫inputVal會報錯,請大神幫我解答下。學習

相關文章
相關標籤/搜索