vue3 composition API 中使用 vuex

下面是一個vue3 composition API 中使用vuex的實例todoList,用到了state,mutations,actions,可以把自己之前用vue2的舊語法改寫成vue3的語法,使用setup,ref, reactive, toRefs,useStore等,完整代碼指路:github: color-library

<!-- todoList.vue -->
<template>
  <div class="todo-list-wrap">
    <h2>{{ title }}</h2>
    <div class="name-wrap">
      <h3>{{ name }}</h3>
      <el-button @click="handleChangeName">
        修改
      </el-button>
      <el-button @click="handleRestoreName">
        還原
      </el-button>
    </div>
    <div class="input-wrap">
      <el-input v-model="inputVal"  @keyup.enter="handleAddItem"></el-input>
      <el-button @click="handleAddItem">
        新增
      </el-button>
    </div>
    <div class="list-item-wrap">
      <div v-for="(item,index) in dataList" :key="index" class="list-item">
        <span>{{ item }}</span>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive, toRefs } from 'vue'
import { useStore } from 'vuex'

  export default {
    name: 'TodoList',
    setup() {
      const title = ref('TodoList')
      const store = useStore()
      const { name } = toRefs(store.state) // 解構
      const inputVal = ref('')
      const dataList = reactive([])
      
      const handleAddItem = ()=> {
        dataList.push(inputVal.value)
        inputVal.value = ''
      }
      const handleChangeName = ()=> {
        // commit和mutations做關聯,提交一個commit,觸發一個mutation
        store.commit('changeName', 'Happy')
      }
      const handleRestoreName = ()=> {
        // dispatch和actions做關聯,派發一個action
        store.dispatch('getData', 'Biblee')
      }
      return {
        title,
        name,
        inputVal,
        dataList,
        handleAddItem,
        handleChangeName,
        handleRestoreName
      }
    }
  }
</script>

<style lang="scss" scoped>
.todo-list-wrap {
  padding: 20px;
  
}
.name-wrap {
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}
.input-wrap {
  width: 300px;
  margin: auto;
  display: flex;
}
.el-button {
  margin-left: 8px;
}
.list-item-wrap {
  padding: 16px;
  .list-item {
    text-align: left;
  }
}
</style>

store:

// store/index.js
import { createStore } from "vuex"

export default createStore({
  state: {
    name: 'Biblee'
  },
  // 同步操作
  mutations: {
    changeName(state, val) {
      state.name = val
    }
  },
  // 異步操作
  actions: {
    getData(store, val) {
      setTimeout(()=>{
        store.commit('changeName',val)
      },2000)
    }
  },
  modules: {

  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章