vuex store

2021/9/10 23:35:22

本文主要是介绍vuex store,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<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

1
2
3
4
5
6
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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'
  }
}

 



这篇关于vuex store的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


原文链接: https://www.cnblogs.com/mingforyou/p/15253387.html
扫一扫关注最新编程教程