[英]vue3 + pinia: how to make reactive a value from the ?store
I am using vue 3 with composition api and pinia我正在使用组合为 api 和 pinia 的 vue 3
I have an auth store that is reading from the store a default email and a default password我有一个正在从商店读取默认 email 和默认密码的授权商店
import { useAuthStore } from "stores/auth";
const authStore = useAuthStore();
const email = authStore.loginUser;
const password = authStore.passwordUser;
Then I am using email and password as v-model
.然后我使用 email 和密码作为v-model
。
The problem is that both are not reactive.问题是两者都不是反应性的。 If I change the value from the text input, the model is not updated如果我更改文本输入的值,则 model 不会更新
I ask kindly for an explanation of the problem and a solution.我恳请对问题的解释和解决方案。
const email = authStore.loginUser
creates an email
constant with the current value of authStore.loginUser
, losing reactivity.使用authStore.loginUser
的当前值创建一个email
常量,失去反应性。 To keep reactivity, you could use computed
:为了保持反应性,您可以使用computed
:
import { computed } from 'vue'
// ...
const email = computed({
get() { return authStore.loginUser },
set(val) { authStore.loginUser = val }
})
...or you could use the provided storeToRefs wrapper, designed for extracting/deconstructing store reactive props while keeping their reactivity (basically to avoid the above boilerplate): ...或者您可以使用提供的storeToRefs包装器,设计用于提取/解构商店反应性道具,同时保持其反应性(基本上是为了避免上述样板):
import { storeToRefs } from 'pinia'
// ...
const {
loginUser: email,
passwordUser: password
} = storeToRefs(authStore)
// email & password are now reactive
Important : you only want to deconstruct state
and getters
using storeToRefs
.重要提示:您只想使用storeToRefs
解构state
和getters
。 Actions should be used directly from the store object ( authStore
in your case) or deconstructed without the wrapper:应直接从商店authStore
(在您的情况下为 authStore)或在没有包装器的情况下解构操作:
const { actionOne, actionTwo } = authStore
This is specified in docs linked above:这是在上面链接的文档中指定的:
... so methods and non reactive properties are completely ignored. ...所以方法和非反应性属性被完全忽略。
In conclusion, you typically end up with two deconstructions from each store:总之,您通常会从每个商店得到两个解构:
import { useSomeStore } from '@/store'
// reactive:
const { s1, s2, g1, g2 } = storeToRefs(useSomeStore())
// non-reactive:
const { a1, a2 } = useSomeStore()
where s1
, s2
are state
members, g1
, g2
are getters
and a1
, a2
are actions
.其中s1
, s2
是state
成员, g1
, g2
是getters
和a1
, a2
是actions
。
I fixed as simply as我固定的很简单
import { useAuthStore } from "stores/auth";
const authStore = useAuthStore();
const email = ref(authStore.loginUser);
const password = ref(authStore.passwordUser);
const rememberme = ref(false);
no useless storeToRefs
used没有使用无用storeToRefs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.