繁体   English   中英

vue3 + pinia:如何从?store 中获取一个值?

[英]vue3 + pinia: how to make reactive a value from the ?store

我正在使用组合为 api 和 pinia 的 vue 3

我有一个正在从商店读取默认 email 和默认密码的授权商店

import { useAuthStore } from "stores/auth";
const authStore = useAuthStore();

const email = authStore.loginUser;
const password = authStore.passwordUser;

然后我使用 email 和密码作为v-model

问题是两者都不是反应性的。 如果我更改文本输入的值,则 model 不会更新

我恳请对问题的解释和解决方案。

const email = authStore.loginUser

使用authStore.loginUser的当前值创建一个email常量,失去反应性。 为了保持反应性,您可以使用computed

import { computed } from 'vue'
// ...

const email = computed({
  get() { return authStore.loginUser },
  set(val) { authStore.loginUser = val }
})

...或者您可以使用提供的storeToRefs包装器,设计用于提取/解构商店反应性道具,同时保持其反应性(基本上是为了避免上述样板):

import { storeToRefs } from 'pinia'
// ...

const { 
  loginUser: email,
  passwordUser: password
} = storeToRefs(authStore) 
// email & password are now reactive 

重要提示:您只想使用storeToRefs解构stategetters 应直接从商店authStore (在您的情况下为 authStore)或在没有包装器的情况下解构操作:

const { actionOne, actionTwo } = authStore

这是在上面链接的文档中指定的:

...所以方法和非反应性属性被完全忽略。


总之,您通常会从每个商店得到两个解构:

import { useSomeStore } from '@/store'
// reactive:
const { s1, s2, g1, g2 } = storeToRefs(useSomeStore())
// non-reactive:
const { a1, a2 } = useSomeStore()

其中s1s2state成员, g1g2gettersa1a2actions

我固定的很简单

import { useAuthStore } from "stores/auth";

const authStore = useAuthStore();

const email = ref(authStore.loginUser);
const password = ref(authStore.passwordUser);
const rememberme = ref(false);

没有使用无用storeToRefs

暂无
暂无

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

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