찾다
웹 프론트엔드JS 튜토리얼Pinia Stores와의 Vue 반응성 이해

Understanding Vue Reactivity with Pinia Stores

직장에서 내부 로컬 개발 작업을 위한 모의 채팅 스토어를 만드는 임무를 맡았는데, 그 동안 Vue에 대해 몇 가지 메모를 했습니다. Hooks), 이것은 단지 내 흑요석 노트입니다. 여러분에게 유용하길 바랍니다 :)

목차

  1. 참조 및 반응 참조
  2. 감시 및 반응성
  3. 피니아 매장 통합
  4. 실제 사례
  5. 모범 사례
  6. 일반적인 문제

Ref 및 반응형 참조

Ref란 무엇인가요?

ref는 기본 값을 반응형으로 만드는 Vue의 방식입니다. .value 속성을 ​​사용하여 반응형 객체의 값을 래핑합니다.

import { ref } from 'vue'

// Inside Pinia Store
export const useMyStore = defineStore('my-store', () => {
  // Creates a reactive reference
  const count = ref<number>(0)

  // To access or modify:
  function increment() {
    count.value++  // Need .value for refs
  }

  return {
    count,  // When exposed, components can use it without .value
    increment
  }
})
</number>

매장 내 Refs 유형

// Simple ref
const isLoading = ref<boolean>(false)

// Array ref
const messages = ref<message>([])

// Complex object ref
const currentUser = ref<user null>(null)

// Ref with undefined
const selectedId = ref<string undefined>(undefined)
</string></user></message></boolean>

감시 및 반응성

기본 시계 사용법

import { watch, ref } from 'vue'

export const useMyStore = defineStore('my-store', () => {
  const messages = ref<message>([])

  // Simple watch
  watch(messages, (newMessages, oldMessages) => {
    console.log('Messages changed:', newMessages)
  })
})
</message>

시청 옵션

// Immediate execution
watch(messages, (newMessages) => {
  // This runs immediately and on changes
}, { immediate: true })

// Deep watching
watch(messages, (newMessages) => {
  // Detects deep object changes
}, { deep: true })

// Multiple sources
watch(
  [messages, selectedId], 
  ([newMessages, newId], [oldMessages, oldId]) => {
    // Triggers when either changes
  }
)

피니아 매장 통합

참조가 있는 저장소 구조

export const useMyStore = defineStore('my-store', () => {
  // State
  const items = ref<item>([])
  const isLoading = ref(false)
  const error = ref<error null>(null)

  // Computed
  const itemCount = computed(() => items.value.length)

  // Actions
  const fetchItems = async () => {
    isLoading.value = true
    try {
      items.value = await api.getItems()
    } catch (e) {
      error.value = e as Error
    } finally {
      isLoading.value = false
    }
  }

  return {
    items,
    isLoading,
    error,
    itemCount,
    fetchItems
  }
})
</error></item>

매장 구성

export const useMainStore = defineStore('main-store', () => {
  // Using another store
  const otherStore = useOtherStore()

  // Watching other store's state
  watch(
    () => otherStore.someState,
    (newValue) => {
      // React to other store's changes
    }
  )
})

실제 사례

자동 새로고침 구현

export const useChatStore = defineStore('chat-store', () => {
  const messages = ref<message>([])
  const refreshInterval = ref<number null>(null)
  const isRefreshing = ref(false)

  // Watch for auto-refresh state
  watch(isRefreshing, (shouldRefresh) => {
    if (shouldRefresh) {
      startAutoRefresh()
    } else {
      stopAutoRefresh()
    }
  })

  const startAutoRefresh = () => {
    refreshInterval.value = window.setInterval(() => {
      fetchNewMessages()
    }, 5000)
  }

  const stopAutoRefresh = () => {
    if (refreshInterval.value) {
      clearInterval(refreshInterval.value)
      refreshInterval.value = null
    }
  }

  return {
    messages,
    isRefreshing,
    startAutoRefresh,
    stopAutoRefresh
  }
})
</number></message>

로딩 상태 관리

export const useDataStore = defineStore('data-store', () => {
  const data = ref<data>([])
  const isLoading = ref(false)
  const error = ref<error null>(null)

  // Watch loading state for side effects
  watch(isLoading, (loading) => {
    if (loading) {
      // Show loading indicator
    } else {
      // Hide loading indicator
    }
  })

  // Watch for errors
  watch(error, (newError) => {
    if (newError) {
      // Handle error (show notification, etc.)
    }
  })
})
</error></data>

모범 사례

1. 참조 초기화

// ❌ Bad
const data = ref()  // Type is 'any'

// ✅ Good
const data = ref<string>([])  // Explicitly typed
</string>

2. 시계 정리

// ❌ Bad - No cleanup
watch(source, () => {
  const timer = setInterval(() => {}, 1000)
})

// ✅ Good - With cleanup
watch(source, () => {
  const timer = setInterval(() => {}, 1000)
  return () => clearInterval(timer)  // Cleanup function
})

3. 계산된 대 감시

// ❌ Bad - Using watch for derived state
watch(items, (newItems) => {
  itemCount.value = newItems.length
})

// ✅ Good - Using computed for derived state
const itemCount = computed(() => items.value.length)

4. 매장 구성

// ✅ Good store organization
export const useStore = defineStore('store', () => {
  // State refs
  const data = ref<data>([])
  const isLoading = ref(false)

  // Computed properties
  const isEmpty = computed(() => data.value.length === 0)

  // Watchers
  watch(data, () => {
    // Handle data changes
  })

  // Actions
  const fetchData = async () => {
    // Implementation
  }

  // Return public interface
  return {
    data,
    isLoading,
    isEmpty,
    fetchData
  }
})
</data>

일반적인 문제

  1. .value를 잊어버린 경우
// ❌ Bad
const count = ref(0)
count++ // Won't work

// ✅ Good
count.value++
  1. 시청 타이밍
// ❌ Bad - Might miss initial state
watch(source, () => {})

// ✅ Good - Catches initial state
watch(source, () => {}, { immediate: true })
  1. 메모리 누수
// ❌ Bad - No cleanup
const store = useStore()
setInterval(() => {
  store.refresh()
}, 1000)

// ✅ Good - With cleanup
const intervalId = setInterval(() => {
  store.refresh()
}, 1000)
onBeforeUnmount(() => clearInterval(intervalId))

기억하세요: Pinia 매장

에서 심판과 시계를 다룰 때는 항상 정리, 유형 안전, 적절한 구성을 고려하세요.

위 내용은 Pinia Stores와의 Vue 반응성 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
JavaScript로 문자열 문자를 교체하십시오JavaScript로 문자열 문자를 교체하십시오Mar 11, 2025 am 12:07 AM

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

사용자 정의 Google 검색 API 설정 자습서사용자 정의 Google 검색 API 설정 자습서Mar 04, 2025 am 01:06 AM

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

예제 색상 JSON 파일예제 색상 JSON 파일Mar 03, 2025 am 12:35 AM

이 기사 시리즈는 2017 년 중반에 최신 정보와 새로운 예제로 다시 작성되었습니다. 이 JSON 예에서는 JSON 형식을 사용하여 파일에 간단한 값을 저장하는 방법을 살펴 봅니다. 키 값 쌍 표기법을 사용하여 모든 종류를 저장할 수 있습니다.

10 JQuery Syntax Highlighter10 JQuery Syntax HighlighterMar 02, 2025 am 12:32 AM

코드 프레젠테이션 향상 : 개발자를위한 10 개의 구문 하이 라이터 웹 사이트 나 블로그에서 코드 스 니펫을 공유하는 것은 개발자에게 일반적인 관행입니다. 올바른 구문 형광펜을 선택하면 가독성과 시각적 매력을 크게 향상시킬 수 있습니다. 티

자신의 Ajax 웹 응용 프로그램을 구축하십시오자신의 Ajax 웹 응용 프로그램을 구축하십시오Mar 09, 2025 am 12:11 AM

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

8 멋진 jQuery 페이지 레이아웃 플러그인8 멋진 jQuery 페이지 레이아웃 플러그인Mar 06, 2025 am 12:48 AM

손쉬운 웹 페이지 레이아웃에 대한 jQuery 활용 : 8 에센셜 플러그인 jQuery는 웹 페이지 레이아웃을 크게 단순화합니다. 이 기사는 프로세스를 간소화하는 8 개의 강력한 JQuery 플러그인을 강조합니다. 특히 수동 웹 사이트 생성에 유용합니다.

10 JavaScript & JQuery MVC 자습서10 JavaScript & JQuery MVC 자습서Mar 02, 2025 am 01:16 AM

이 기사는 JavaScript 및 JQuery Model-View-Controller (MVC) 프레임 워크에 대한 10 개가 넘는 튜토리얼을 선별 한 것으로 새해에 웹 개발 기술을 향상시키는 데 적합합니다. 이 튜토리얼은 Foundatio의 다양한 주제를 다룹니다

' this ' 자바 스크립트로?' this ' 자바 스크립트로?Mar 04, 2025 am 01:15 AM

핵심 포인트 JavaScript에서는 일반적으로 메소드를 "소유"하는 객체를 말하지만 함수가 호출되는 방식에 따라 다릅니다. 현재 객체가 없으면 글로벌 객체를 나타냅니다. 웹 브라우저에서는 창으로 표시됩니다. 함수를 호출 할 때 이것은 전역 객체를 유지하지만 객체 생성자 또는 그 메소드를 호출 할 때는 객체의 인스턴스를 나타냅니다. call (), apply () 및 bind ()와 같은 메소드를 사용 하여이 컨텍스트를 변경할 수 있습니다. 이 방법은 주어진이 값과 매개 변수를 사용하여 함수를 호출합니다. JavaScript는 훌륭한 프로그래밍 언어입니다. 몇 년 전,이 문장은있었습니다

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구