You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 3的Watch功能在Pinia中的等价实现方案

迁移组件Watcher到Pinia的实现方案

1. 创建Pinia Store

先把原组件里的状态和异步请求逻辑迁移到Pinia Store中,实现状态集中管理:

// stores/tldStore.js
import { defineStore } from 'pinia'
import axios from 'axios'

export const useTldStore = defineStore('tld', {
  state: () => ({
    filters: {
      searchedTlds: '',
      tlds: []
    }
  }),
  actions: {
    async fetchSearchedTlds() {
      try {
        const response = await axios.get('/fetch-checked-tlds', {
          params: { searchedTlds: this.filters.searchedTlds }
        })
        this.filters.tlds = response.data.tlds
        console.log(response.data.tlds)
      } catch (error) {
        console.log(error)
      } finally {
        // 这里可以放置需要始终执行的逻辑
      }
    }
  },
  // 在Store内部监听状态变化
  setup() {
    const store = useTldStore()
    watch(
      () => store.filters.searchedTlds,
      () => {
        store.fetchSearchedTlds()
      },
      { immediate: true } // 可选:初始化时自动执行一次请求
    )
    return {}
  }
})

2. 组件中使用Store

组件无需再维护本地状态和Watcher,直接引入Store并绑定数据即可:

<template>
  <div>
    <input 
      type="text" 
      v-model="tldStore.filters.searchedTlds" 
      placeholder="搜索域名后缀..."
    />
    <div v-for="tld in tldStore.filters.tlds" :key="tld">
      <input type="checkbox" :value="tld" /> {{ tld }}
    </div>
  </div>
</template>

<script setup>
import { useTldStore } from '@/stores/tldStore'

const tldStore = useTldStore()
</script>

3. 可选:在组件中监听Store状态

如果更倾向于在组件层面控制监听逻辑,也可以保留组件内的Watcher,直接监听Store的状态变化:

<script setup>
import { useTldStore } from '@/stores/tldStore'
import { watch } from 'vue'

const tldStore = useTldStore()

watch(
  () => tldStore.filters.searchedTlds,
  () => {
    tldStore.fetchSearchedTlds()
  },
  { immediate: true }
)
</script>

补充说明

  • Laravel控制器代码无需修改,接口查询逻辑保持原样即可
  • 推荐使用Store内部的Watcher方案,让状态相关逻辑完全集中在Store中,符合Pinia的状态管理设计思路
  • 用async/await替代原有的then/catch写法,让异步代码更简洁易读

内容的提问来源于stack exchange,提问作者summer9844

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:55:26