Vuex 4 — 모듈
                                            
                                                
                                                
                                                
                                                
                                                
                                                 7090 단어  vueprogrammingjavascriptwebdev
                    
지금 http://jauyeung.net/subscribe/에서 내 이메일 목록을 구독하십시오.
Vuex 4는 베타 버전이며 변경될 수 있습니다.
Vuex는 Vue의 인기 있는 상태 관리 라이브러리입니다.
Vuex 4는 Vue 3에서 작동하도록 만들어진 버전입니다.
이 기사에서는 Vue 3에서 Vuex 4를 사용하는 방법을 살펴보겠습니다.
모듈
상태를 여러 개의 작은 부분으로 나눌 수 있도록 Vuex 4 저장소를 모듈로 나눌 수 있습니다.
각 모듈에는 고유한 상태, 돌연변이, 작업 및 게터가 있습니다.
모듈 로컬 상태
각 모듈에는 고유한 로컬 상태가 있습니다. 다음과 같이 작성하여 모듈의 상태를 계산된 속성에 매핑하고 변형을 메서드에 매핑할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <button @click="increment">increment</button>
      <p>{{doubleCount}}</p>
    </div>
    <script>
      const moduleA = {
        state: () => ({
          count: 0
        }),
        mutations: {
          increment(state) {
            state.count++;
          }
        },
        getters: {
          doubleCount(state) {
            return state.count * 2;
          }
        }
      };
      const store = new Vuex.Store({
        modules: {
          moduleA
        }
      });
      const app = Vue.createApp({
        methods: {
          ...Vuex.mapMutations(["increment"])
        },
        computed: {
          ...Vuex.mapGetters(["doubleCount"])
        }
      });
      app.use(store);
      app.mount("#app");
    </script>
  </body>
</html>
스토어에 모듈을 포함하기 위해
modules 속성으로 스토어를 생성했습니다.그런 다음 Vue 인스턴스에는
mapMutations 및 mapGetters 메서드가 있어 돌연변이를 메서드에 매핑하고 게터를 계산된 속성에 매핑합니다.우리는 행동과 상태에서도 똑같이 할 수 있습니다.
예를 들어 다음과 같이 작성할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <button @click="increment">increment</button>
      <p>{{moduleA.count}}</p>
    </div>
    <script>
      const moduleA = {
        state: () => ({
          count: 0
        }),
        mutations: {
          increment(state) {
            state.count++;
          }
        },
        actions: {
          increment({ commit }) {
            commit("increment");
          }
        }
      };
      const store = new Vuex.Store({
        modules: {
          moduleA
        }
      });
      const app = Vue.createApp({
        methods: {
          ...Vuex.mapActions(["increment"])
        },
        computed: {
          ...Vuex.mapState({ moduleA: (state) => state.moduleA })
        }
      });
      app.use(store);
      app.mount("#app");
    </script>
  </body>
</html>
작업 이름 배열을 사용하여
mapActions 메서드를 호출했습니다.mapState 메서드는 모듈 상태를 반환하는 메서드가 있는 개체와 함께 호출됩니다.상태는 속성 이름으로 모듈 이름을 가진 개체에 있습니다.
네임스페이스
모듈의 이름을 지정할 수 있습니다.
이렇게 하면 하나의 전역 네임스페이스 아래에 모든 것이 포함되지 않습니다.
또한 이를 통해 여러 모듈이 동일한 돌연변이 또는 작업 유형에 반응할 수 있습니다.
예를 들어 다음과 같이 작성할 수 있습니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <button @click="this['moduleA/increment']">increment</button>
      <p>{{moduleA.count}}</p>
    </div>
    <script>
      const moduleA = {
        state: () => ({
          count: 0
        }),
        mutations: {
          increment(state) {
            state.count++;
          }
        },
        actions: {
          increment({ commit }) {
            commit("increment");
          }
        }
      };
      const store = new Vuex.Store({
        modules: {
          moduleA: {
            namespaced: true,
            ...moduleA
          }
        }
      });
      const app = Vue.createApp({
        methods: {
          ...Vuex.mapActions(["moduleA/increment"])
        },
        computed: {
          ...Vuex.mapState({ moduleA: (state) => state.moduleA })
        }
      });
      app.use(store);
      app.mount("#app");
    </script>
  </body>
</html>
namespaced 속성을 true 로 설정했기 때문에 작업을 네임스페이스 이름으로 매핑했습니다.우리는 게터와 돌연변이로 같은 일을 할 수 있습니다.
이를 위해 다음과 같이 작성합니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.global.js"></script>
    <title>App</title>
  </head>
  <body>
    <div id="app">
      <button @click="this['moduleA/increment']">increment</button>
      <p>{{this['moduleA/doubleCount']}}</p>
    </div>
    <script>
      const moduleA = {
        state: () => ({
          count: 0
        }),
        mutations: {
          increment(state) {
            state.count++;
          }
        },
        getters: {
          doubleCount(state) {
            return state.count;
          }
        }
      };
      const store = new Vuex.Store({
        modules: {
          moduleA: {
            namespaced: true,
            ...moduleA
          }
        }
      });
      const app = Vue.createApp({
        methods: {
          ...Vuex.mapMutations(["moduleA/increment"])
        },
        computed: {
          ...Vuex.mapGetters(["moduleA/doubleCount"])
        }
      });
      app.use(store);
      app.mount("#app");
    </script>
  </body>
</html>
모듈에서
mapMutations를 mapGetters로 설정했기 때문에 네임스페이스 이름으로 namespaced 및 true를 호출했습니다.결론
자체 상태를 관리하는 저장소의 여러 작은 부분을 가질 수 있도록 모듈을 만들고 이름 공간을 지정할 수 있습니다.
Reference
이 문제에 관하여(Vuex 4 — 모듈), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aumayeung/vuex-4-modules-3m07텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)