moduleA.ts
const moduleA = {
// strict:true,
// strict:process.env.NODE_NEV !== 'production',
// 全局共享的状态(数据)存放
state: {
counter : 0
},
getters: {
},
// 同步提交状态
mutations: {
//加1
INCREMENT(state: { counter: number; }){
state.counter++;
},
//减1
DECREMENT(state: { counter: number; }){
state.counter--;
},
//加2
INCREMENT2(state: { counter: any; },num: any){
setTimeout(()=>{
state.counter+=num;
},2000)
// state.counter+=num;
},
},
// 提交操作(可以是同步也可以是异步)给mutations
actions: {
//加1
increment(context: any){
context.commit('INCREMENT');
},
//减1
decrement(context: any){
context.commit('DECREMENT');
},
//加2
increment2(context: any){
context.commit('INCREMENT2');
// setTimeout(()=>{
// commit('INCREMENT2');
// },2000)
},
}
}
export default moduleA;
index.ts
import { createStore } from 'vuex';
import state from './state';
import getters from './getters';
import mutations from './mutations';
import actions from './actions';
import moduleA from './modules/moduleA';
const store = createStore({
// // strict:true,
// // strict:process.env.NODE_NEV !== 'production',
// // 全局共享的状态(数据)存放
// state: {
// counter : 0
// },
// getters: {
// },
// // 同步提交状态
// mutations: {
// //加1
// INCREMENT(state){
// state.counter++;
// },
// //减1
// DECREMENT(state){
// state.counter--;
// },
// //加2
// INCREMENT2(state,num){
// setTimeout(()=>{
// state.counter+=num;
// },2000)
//
// // state.counter+=num;
// },
// },
// // 提交操作(可以是同步也可以是异步)给mutations
// actions: {
// //加1
// increment({commit}){
// commit('INCREMENT');
// },
// //减1
// decrement({commit}){
// commit('DECREMENT');
// },
// //加2
// increment2({commit}){
// commit('INCREMENT2');
//
// // setTimeout(()=>{
// // commit('INCREMENT2');
// // },2000)
// },
// },
// modules: {
// }
state,
getters,
mutations,
actions,
modules: {
a: moduleA
}
});
export default store
<template>
<div class="about">
<h1>This is an about page</h1>
<h2>{{$store.state.a.counter}}</h2>
<button @click="add">++</button>
<button @click="sub">--</button>
<button @click="add2(100)">+++</button>
<button @click="addItem">addItem</button>
<button @click="changeItem">changeItem</button>
</div>
</template>
<script>
import {useStore} from 'vuex';
import {computed} from 'vue';
export default {
setup(props){
const store = useStore();
const todos = computed(()=> store.state.todos)
const add = ()=>{
store.dispatch('increment');
// store.commit('INCREMENT');
}
const sub = ()=>{
store.dispatch('decrement');
// store.commit('DECREMENT');
}
const add2 = (num)=>{
// store.dispatch('increment2',num);
store.commit('INCREMENT2',num);
}
let addItem = ()=>{
console.log("addItem");
store.dispatch('addTodo', {id:'',name:'赵六'});
console.log(todos.value);
}
const delItem = ()=>{
if(window.confirm('确认删除?')){
store.dispatch('delTodo',props.index);
}
}
let changeItem = ()=>{
console.log("changeItem:"+todos.value);
store.dispatch('changeTodo');
console.log("============"+todos.value);
}
return{
add,
add2,
sub,
addItem,
delItem,
changeItem
}
}
}
</script>