Vue3 Bunny Fresh: Pinia 시작하기
날짜: 2023년 5월 11일
합계: Pinia 개념, 카운터, 게터, 비동기 작업 구현, storeToRefs 및 반응형 해체 유지
피니아란?
Pinia는 Vue의 전용 상태 관리 라이브러리로 구성 요소 또는 페이지 간에 상태를 공유할 수 있으며 vuex 상태 관리 도구를 대체합니다.Vuex와 비교하여 다음과 같은 장점이 있습니다.
- 더 간단한 API 제공(변형 제거)
- 결합된 API 스타일을 준수하는 API 제공(Vue3의 새로운 구문으로 통합)
- 모듈의 개념을 제거하고 각 매장은 독립적인 모듈입니다.
- TypeScript와 함께 작동하여 신뢰할 수 있는 유형 추론 제공
중국어 문서: https://pinia.vuejs.org/zh
빈 Vue 프로젝트 생성 및 Pinia 설치
1. 빈 Vue 프로젝트 생성
npm init vue@latest
2. Pinia 설치 및 등록
npm i pinia
import { createPinia } from 'pinia'
const app = createApp(App)
// 以插件的形式注册
app.use(createPinia())
app.use(router)app.mount('#app')
카운터 구현
핵심 단계:
-
스토어 정의
-
구성 요소 사용 저장소
1- 매장 정의
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', ()=>{
// 数据 (state)
const count = ref(0)
// 修改数据的方法 (action)
const increment = ()=>{
count.value++
}
// 以对象形式返回
return {
count,
increment
}
})
이해하다:
스토어를 정의할 때 결합된 API와 동일한 작성 방식을 채택하되, 필요한 데이터와 메소드를 반환해야 합니다.
2- 구성 요소 사용 저장소
<script setup>
// 1. 导入use方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到store实例对象 store里有数据和方法
const counterStore = useCounterStore()
</script>
<template>
<button @click="counterStore.increment">
{
{ counterStore.count }}
</button>
</template>
사례:
counter.js
// 导入一个方法 defineStore
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter' , () => {
// 定义数据(state)
const count = ref(0)
// 定义修改数据的方法(action 同步+异步)
const increment = () => {
count.value++
}
// 以对象的方式return供组件使用
return {
count,
increment
}
})
app.vue
<template>
<button @click="counterStore.increment">{
{ counterStore.count }}</button>
</template>
<script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore);
</script>
<style>
</style>
효과: 카운터 구현
게터 구현
게터는 계산된 속성을 사용하여 직접 구현할 수 있습니다.
구현: 여기서 doubleCount는 개수가 변경되면 항상 변경됩니다.
// 数据(state)
const count = ref(0)
// getter (computed)
const doubleCount = computed(() => count.value * 2)
비동기 작업
아이디어: 액션 함수는 구성 요소에서 네트워크 요청을 보내는 작성 방법과 일치하는 동기식 및 비동기식을 모두 지원합니다.
단계: 1. 저장소에서 작업 정의 2. 구성 요소에서 작업 트리거
1- 상점에서 조치 정의
const API_URL = 'http://geek.itheima.net/v1_0/channels'
export const useCounterStore = defineStore('counter', ()=>{
// 数据
const list = ref([])
// 异步action
const loadList = async ()=>{
const res = await axios.get(API_URL)
list.value = res.data.data.channels
}
return {
list,
loadList
}
})
2- 컴포넌트에서 액션 호출
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
// 调用异步action
counterStore.loadList()
</script>
<template>
<ul>
<li v-for="item in counterStore.list" :key="item.id">{
{ item.name }}</li>
</ul>
</template>
storeToRefs는 응답성 파괴를 유지합니다.
저장소를 기반으로 직접 분해 및 할당하면 응답 데이터(상태 및 게터)가 응답 특성을 잃게 됩니다. storeToRefs를 사용하여 응답성을 유지하는 데 도움이 됩니다.
구체적인 조작:
<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
// 使用它storeToRefs包裹之后解构保持响应式
const { count } = storeToRefs(counterStore)
const { increment } = counterStore
</script>
<template>
<button @click="increment">
{
{ count }}
</button>
</template>
이해: 데이터 및 메서드가 할당을 분해하는 방법
데이터 구조화 할당:
구조 분해 할당 사용 및 메서드 래핑 사용
메소드 해체 할당:
그냥 분해하고 할당
app.vue
<template>
<button @click="increment">{
{ count }}</button>
<p>{
{ doubleCount }}</p>
<ul>
<li v-for="item in counterStore.getList" :key="item.id">{
{ item.name }}</li>
</ul>
</template>
<script setup>
// 1. 导入 use 打头的方法
import { useCounterStore } from '@/stores/counter'
import { onMounted } from 'vue'
import { storeToRefs } from 'pinia'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
// 数据解构:
// 直接解构赋值(会造成响应式丢失)
// 这里采用方法包裹(可以保持响应式的更新)
const { count, doubleCount } = storeToRefs(counterStore)
// 方法解构:
// 注: 方法解构直接从counterStore中解构赋值即可
const { increment } = counterStore
onMounted(() => {
counterStore.getList()
})
</script>
효과:
알아채다:
그림과 같이 할당을 직접 분해하면 값만 되돌려줍니다. 그리고 구조 분해 할당을 사용하고 메서드 래핑을 사용한 다음 개체를 반환합니다.
요약하다:
-
pinias는 무엇을 위해 사용됩니까?
차세대 vuex인 중앙 집중식 상태 관리 도구
-
Pinia에서 돌연변이가 여전히 필요합니까?
아니요, action은 동기식과 비동기식을 모두 지원합니다
Pinia는 getter를 어떻게 구현합니까?
계산 계산 속성 함수 -
Pinia가 생성한 Store는 응답성을 유지하기 위해 어떻게 데이터를 분해하고 할당합니까?
storeToRefs