src/store/index.ts
- 删除编辑功能未完成 ```typescript import { createStore } from “vuex”;
const store = createStore({ modules: { todoListStore: { namespaced: true, state: { list: [], }, actions: { addtodo(store, data) { const action = { type: “ADDTODO”, payload: data.todoitem, }; store.commit(action); }, }, mutations: { ADDTODO(state, action) { state.list.unshift({ id:state.list.length+1, task:action.payload }) }, }, }, }, }); export default store;
scr/components/todoList.vue
```vue
<template>
<div>
<h1>todoList</h1>
<input type="text" @keydown.enter="add" v-model="todoitem" />
<ul>
<li v-for="item in list" :key="item.id">
<span>{{item.task}}</span><button>edit</button><button>delete</button>
</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent, computed, reactive,toRefs } from "vue";
import { useStore } from "vuex";
export default defineComponent({
setup() {
const state =reactive({
todoitem:''
})
const store = useStore();
const list = computed(() => store.state.todoListStore.list);
const add=()=>{
store.dispatch({
type:"todoListStore/addtodo",
todoitem:state.todoitem
})
state.todoitem=''
}
return{
list,add,...toRefs(state)
}
},
});
</script>
优化:
使用ES6的结构优化代码
actions: {
// addtodo(store, data) {
// const action = {
// type: "ADDTODO",
// payload: data.todoitem,
// };
// store.commit(action);
// },
addtodo({commit}, {todoitem}) {
commit({
type: "ADDTODO",
payload: todoitem,
});
},
},
// mutations: {
// ADDTODO(state, action) {
// state.list.unshift({
// id:state.list.length+1,
// task:action.payload
// })
// },
// },
mutations: {
ADDTODO({list}, {payload}) {
list.unshift({
id:list.length+1,
task:payload
})
},
},
将modules中每一项抽离成一个文件
好处:一个文件一个数据库
store下创建todoListStore.ts
// 用于约定17行commit类型
import { Commit } from "vuex";
// 导出
export default {
namespaced: true,
state: {
list: [],
},
actions: {
addtodo(
{ commit }: { commit: Commit },
{ todoitem }: { todoitem: string }
) {
commit({
type: "ADDTODO",
payload: todoitem,
});
},
},
mutations: {
ADDTODO({ list }: { list: unknown[] }, { payload }: { payload: string }) {
list.unshift({
id: list.length + 1,
task: payload,
});
},
},
};
在store/index.ts引入
import { createStore } from "vuex";
import * as api from "../api";
// 导入
import todoListStore from './todoListStore'
const store = createStore({
modules: {
moviesStore:{
....
},
countStore:{
....
},
todoListStore // 直接使用
}
});
export default store;