[英]Conditionally accessing Pinia value from template in Vue 3
僅當從我的Pinia
商店訪問的值是 true 時,我才嘗試渲染組件 -
// MessageArea.vue
import { useValidationStore } from '../../stores/ValidationStore.js'
data() {
return {
errors: {
english: useValidationStore().english.error,
},
}
},
<template>
<p v-if="errors.english">
<EnglishErrorMessage />
</p>
</template>
默認情況下,它是false
-
import { defineStore } from "pinia";
export const useValidationStore = defineStore("validation", {
state: () => {
return {
english: {
input: '',
error: false,
},
}
}
})
我還從另一個文件訪問相同的值以檢查錯誤 -
<script>
import { useValidationStore } from '../../../stores/ValidationStore';
export default {
data() {
return {
input: useValidationStore().english.message,
error: useValidationStore().english.error,
}
},
methods: {
validate(input) {
this.input = input.target.value
const legalChars = /^[A-Za-z\s]*$/.test(this.input);
if (!legalChars && this.input !== "") {
this.error = true;
} else if (this.input === "" || (legalChars && !legalChars)) {
this.error = false;
}
console.log(this.error)
console.log(this.input)
}
}
}
</script>
<template>
<input
@input="validate"
:value="input"
/>
</template>
控制台日志值正在被動更新。 此外,當在輸入中輸入非法字符時, this.error
將被記錄為 true。 反應性表現符合預期。 所以,我不確定為什么 '' 在這種情況下不會呈現?
我沒有在模板中正確訪問 pinia 值嗎?
我試圖從文檔中了解什么是“mapState()”和“mapStores()”,以及它們是否可以幫助我,但我仍然感到困惑。
您需要在validate
方法中更改商店 state。 如果您想在options api
中使用 pinia,您可以在計算屬性中使用mapState
和mapWritableState
以保持激活。 請看看這里的codesandbox
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.