vuex store
index.ts
import { createStore } from 'vuex'
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: {
}
});
export default store
about.vue
<template> <div class="about"> <h1>This is an about page</h1> <h2>{{$store.state.counter}}</h2> <button @click="add">++</button> <button @click="sub">--</button> <button @click="add2(100)">+++</button> </div> </template> <script> import {useStore} from 'vuex'; export default { setup(){ const store = useStore(); 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); } return{ add, add2, sub } } } </script>
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(store).use(router).mount('#app')
.eslintrc.js
module.exports = { root: true, env: { node: true }, extends: [ 'plugin:vue/vue3-essential', // '@vue/standard', '@vue/typescript/recommended' ], parserOptions: { ecmaVersion: 2020 }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' } }