首頁  >  文章  >  web前端  >  了解 Vue 與 Pinia Store 的反應性

了解 Vue 與 Pinia Store 的反應性

Barbara Streisand
Barbara Streisand原創
2024-11-20 15:51:14572瀏覽

Understanding Vue Reactivity with Pinia Stores

在我的工作場所,我的任務是為內部本地開發工作創建一個模擬聊天商店,在這樣做的同時,我做了一些關於Vue 的筆記(我有一些經驗,但沒有hooks),所以這只是我的黑曜石筆記,希望對你有用:)

目錄

  1. 參考與反應參考
  2. 觀看與反應
  3. Pinia 商店整合
  4. 實際範例
  5. 最佳實踐
  6. 常見問題

參考文獻與反應參考文獻

什麼是參考?

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
  }
})

商店中的參考文獻類型

// 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)

觀察和反應

手錶的基本使用

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)
  })
})

觀看選項

// 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
  }
)

Pinia 商店集成

帶有引用的儲存結構

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
  }
})

組合商店

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
  }
})

載入狀態管理

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.)
    }
  })
})

最佳實踐

1. 參考初始化

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

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

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
  }
})

常見問題

  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 商店

與裁判和手錶合作時,請始終考慮清理、類型安全和適當的組織

以上是了解 Vue 與 Pinia Store 的反應性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn