简体   繁体   English

Vue3 | Pinia - 在可组合函数中观看 storeToRefs 不起作用

[英]Vue3 | Pinia - Watching storeToRefs in composable function does not work

I'm trying to understand the purpose of composables.我试图了解可组合的目的。 I have a simple composable like this and was trying to watch state from a Pinia store where the watch does not trigger:我有一个像这样的简单组合,并试图从watch不触发的 Pinia 商店观看状态:

import { ref, watch, computed } from "vue";
import { storeToRefs } from "pinia";
import useFlightsStore from "src/pinia/flights.js";
import usePassengersStore from "src/pinia/passengers.js";

export function useFlight() {
    const route = useRoute();

    const modalStore = useModalStore();
    const flightsStore = useFlightsStore();
    const { selection } = storeToRefs(flightsStore);

    const passengersStore = usePassengersStore();
    const { passengers, adults, children, infants } =
        storeToRefs(passengersStore);

    watch([adults, children, infants], (val) => console.log('value changes', val))


Where as the same thing in a Vue component works as expected.在 Vue 组件中,同样的东西可以按预期工作。

So we cannot watch values inside composables?所以我们不能观察可组合物中的值吗?

I think you can watch values inside composables.我认为您可以查看可组合物中的值。

But, to watch a pinia state it has to be inside an arrow function:但是,要查看 pinia 状态,它必须在箭头函数内:

watch(() => somePiniaState, (n) => console.log(n, " value changed"));

It's like watching a reactive object.这就像看一个反应物体。


I believe this should be documented better.我相信这应该更好地记录下来。 In Pinia documentation we can read how to watch the whole store or how to subscribe to a store but not how to watch a single state property inside a component or composable.在 Pinia 文档中,我们可以阅读如何查看整个商店或如何订阅商店,但不能阅读如何查看组件或可组合中的单个状态属性。

Also, the docs are somewhat shy in explaining that you can watch a property inside a store using setup() way of describing a store.此外,文档有点害羞地解释说您可以使用setup()描述商店的方式来查看商店内的属性。

More on this here: https://github.com/vuejs/pinia/discussions/794#discussioncomment-1643242更多信息在这里: https ://github.com/vuejs/pinia/discussions/794#discussioncomment-1643242


This error also silently fails (or does not execute), which is not helpful...此错误也会静默失败(或不执行),这无济于事......

I needed to watch a specific state attribute in one of my components but I didn't find my use case on the official documentation .我需要查看我的一个组件中的特定状态属性,但我在官方文档中没有找到我的用例。 I used a mix between a watch and storeToRefs to do it.我使用了手表和 storeToRefs 之间的混合来做到这一点。

import { usePlaylistsStore } from '@/stores/playlists'
import { storeToRefs } from 'pinia'
export default {
    name: 'PlaylistDetail',

    setup() {
        const playlistsStore = usePlaylistsStore()
        const { selectedGenres } = storeToRefs(playlistsStore)
        return { selectedGenres }
    },
    watch: {
        selectedGenres(newValue, oldValue) {
            // do something
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM