简体   繁体   English

有条件地从 Vue 3 中的模板访问 Pinia 值

[英]Conditionally accessing Pinia value from template in Vue 3

I'm trying to render a component only if the value accessed from my Pinia store is true -仅当从我的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>

By default, it is false -默认情况下,它是false -

import { defineStore } from "pinia";

export const useValidationStore = defineStore("validation", {
    state: () => {
        return {
            english: {
                input: '',
                error: false,
            },
        }
    }
})

I'm also accessing that same value from another file to check for the error -我还从另一个文件访问相同的值以检查错误 -

<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>

The console log values are updating reactively.控制台日志值正在被动更新。 Also, this.error will be logged as true when an illegal character is entered into the input.此外,当在输入中输入非法字符时, this.error将被记录为 true。 The reactivity is behaving as expected.反应性表现符合预期。 So, I'm not sure why '' will not render in this case?所以,我不确定为什么 '' 在这种情况下不会呈现?

Am I not accessing the pinia value correctly in the template?我没有在模板中正确访问 pinia 值吗?

I've tried to understand what 'mapState()' and 'mapStores()' from the docs and if they can help me but I'm still confused.我试图从文档中了解什么是“mapState()”和“mapStores()”,以及它们是否可以帮助我,但我仍然感到困惑。

You need to mutate the store state in validate method.您需要在validate方法中更改商店 state。 If you want to use pinia in options api you can use mapState and mapWritableState in computed property to remain rective.如果您想在options api中使用 pinia,您可以在计算属性中使用mapStatemapWritableState以保持激活。 Take a look here codesandbox please.请看看这里的codesandbox

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

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