blog

vue3+ts 프로젝트에서 vuex 사용

vuex의 사용 및 소개, vuex 상태 가져오기 변이 작업 모듈의 5가지 주요 속성, vuex의 전체 코드;...

Apr 28, 2025 · 4 min. read
シェア

프리앰블

이 기사에서는 뷰엑스의 사용법을 요약하고, 뷰엑스에 대한 다섯 가지 속성의 사용을 소개하고, 다음은 각 속성에 대한 자세한 설명이 있으며, 기사 끝에 전체 코드가 있으며, 프로젝트에 복사 할 수 있으며, 자신의 뷰의 효과를 볼 수 있습니다.

뷰엑스의 다섯 가지 속성: 상태 가져오기 돌연변이 액션 모듈

state

상태는 뷰엑스의 기본 데이터이며 변수를 저장하는 데 사용됩니다.

getters

상태의 계산된 속성에 해당하는 기본 데이터에서 파생된 데이터는 store.getters.computed 속성 이름을 사용하여 호출되는 상점의 게터에 정의됩니다.

mutations

변경은 업데이트된 데이터를 커밋하는 메소드이며 동기화해야 합니다. 상태 변수를 조작할 메서드를 뮤테이션에 정의하고 화면에 표시된 메서드에서 store.commit()을 통해 뮤테이션의 메서드를 호출하여 상태 조작을 수행합니다.

actions

액션은 돌연변이와 유사하지만 돌연변이 대신 비동기 연산을 수행하는 함수로 사용됩니다.

modules

모듈: 각 모듈은 고유한 상태, 변이, 액션 및 게터를 가질 수 있으므로 구조가 매우 명확하고 관리하기 쉽습니다. 모듈에서 다섯 가지 주요 속성의 사용은 상점의 다섯 가지 속성과 유사합니다. 차이점은 작업 데이터가 다른 위치에 저장된다는 점입니다. 편리한 관리

전체 코드:

main.ts

// import store from "./store"; createApp(App).use(store)

store/index.ts

//import Vuex from "vuex"; import { createStore } from "vuex"; interface stuObj { id: number; name: string; age: number; } interface State { count: number; myName: string; students: Array<stuObj>; } interface moduleState { moduleName: string; } const moduleA = { state: { moduleName: "moduleA" }, getters: { fullName(state: moduleState) { return state.moduleName + ",moduleA의 계산된 속성 "; } } }; const moduleB = { state: { moduleName: "moduleB" }, getters: { fullName(state: moduleState) { return state.moduleName + ",moduleB의 계산된 속성 "; } } }; // //export default new Vuex.Store({ export default createStore<State>({ //구성(상태|mutations|actions) state: { //관리되는 데이터 count: 10, myName: "lz", students: [ { id: 110, name: "zhao", age: 19 }, { id: 111, name: "qian", age: 17 }, { id: 112, name: "sun", age: 28 }, { id: 113, name: "li", age: 8 } ] }, getters: { //계산된 속성 getMyName(state: State) { //state매개 변수는 고정되어 있으며 state 값을 가져오는 것을 참조합니다. return state.myName + "속성 계산하기 ah"; }, more20Stu(state: State) { return state.students.filter((s) => s.age > 20); }, moreAgeStu(state: State) { return function (age: number) { //배열의 새로운 기능인 filter,filter() 메서드를 호출하면 새 배열이 생성되고, 새 배열의 요소는 배열의 //의 모든 요소 return state.students.filter((s) => s.age > age); }; } }, mutations: { //this.$store.commit('increment') increment(state: State) { state.count++; }, incrementCount(state: State, count: number) { state.count += count; }, decrement(state: State) { state.count--; }, updateNameInfo(state: State, value) { state.myName = value; } }, actions: { //actions변수와 유사하지만 비동기 연산에 변수 대신 사용되는 함수 updateName(context, payload) { setTimeout(() => { context.commit("updateNameInfo", payload); }, 1000); }, promiseUpdateName(context, payload) { return new Promise((resolve, reject) => { setTimeout(() => { context.commit("updateNameInfo", payload); resolve("성공적으로 수정됨"); }, 1000); }); } }, modules: { a: moduleA, b: moduleB } });

views/parent.vue

<template>
 <div>
 
 {{ store.state.count }}
 <h2>-------vue속성 게터 계산하기 --------</h2>
 <h3>계산된 속성에 대한 getMyName의 값을 가져옵니다:{{ store.getters.getMyName }}</h3>
 <h3>객체에 대한 vuex 게터를 통해 20세 이상의 주 학생을 가져오는 방법은 다음과 같습니다.: {{ store.getters.more20Stu }}</h3>
 <h3>계산된 프로퍼티에 값을 전달하려면 값을 받는 메서드를 반환해야 합니다:{{ store.getters.moreAgeStu(18) }}</h3>
 <hr />
 <h1>-------mutations--------</h1>
 <h2>store쇼케이스의 카운트 값{{ store.state.count }}</h2>
 <button @click="addtion">+</button>
 <button @click="subtion">-</button>
 <button @click="addCount(5)">+5</button>
 <button @click="addCount(10)">+10</button>
 <hr />
 <h1>-------actions--------</h1>
 <h2>액션을 통해 이름 수정:{{ store.state.myName }}</h2>
 <button @click="updateName">수정 사항 결정</button>
 <button @click="promiseUpdateName">promise콜백 수정</button>
 <br />
 <h1>-------modules--------</h1>
 <h2>modulesA:{{ store.state.a.moduleName }}</h2>
 <h2>modulesB:{{ store.state.b.moduleName }}</h2>
 </div>
</template>
<script lang="ts" setup>
//페이지 소개
import { useStore } from "vuex";
const store = useStore();
const addtion = () => {
 store.commit("increment");
};
function subtion() {
 store.commit("decrement");
}
function addCount(count: number) {
 store.commit("incrementCount", count);
}
function updateName() {
 store.dispatch("updateName", "action");
}
function promiseUpdateName() {
 store.dispatch("promiseUpdateName", "운반된 정보").then((res: any) => {
 alert("action변경 사항이 커밋되어 매개변수:"와 함께 반환되었습니다.", +res);
 });
}
</script>
Read next

오픈 소스 빅 모델 프레임워크 개요 3.1 TensorFlow 및 Keras3.1.1 TensorFlow 소개

1.배경 Google에서 개발한 오픈 소스 딥 러닝 프레임워크입니다. 신경망을 구축하고 훈련하는 데 사용할 수 있으며 CPU, GPU, TPU와 같은 하드웨어에서 실행할 수 있습니다. 설계 목표는 유연하고 고도의 성능을 제공하는 것입니다.

Apr 26, 2025 · 9 min read