我在组件中提供变量,并在其子组件中注入(inject)/更改它们。这在本地服务器上工作正常,但上传到服务器后,变量似乎没有改变。
我使用组合API。
组件A(父级)
import { provide, ref } from 'vue';
const loggedIn = ref(false);
provide('global', loggedIn);
const credentials = ref(true);
provide('credentials', credentials);
组件 B(子组件)
<script setup lang="ts">
import {
IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
} from "@ionic/vue";
import router from "@/router";
import { inject, ref } from "vue";
const global: boolean = inject("global") as boolean;
const credentials: boolean = inject("credentials") as boolean;
function greet(global: boolean, credentials: boolean) {
const usr = document.querySelector("input[name=email]").value;
const pass = document.querySelector("input[name=password]").value;
if (
usr === "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2b39293f380c2b39293f38622f2321" rel="noreferrer noopener nofollow">[email protected]</a>" &&
pass === "guest123#"
) {
this.global = true;
this.credentials = false;
router.push("/app");
}
}
</script>
VS Code 显示 this.global = true 和 this.credentials = false 的两个警告:
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
HomePage.vue(19, 10): An outer value of 'this' is shadowed by this container.
有什么办法可以解决这个问题吗?
最佳答案
注入(inject)
默认情况下不是 react 性的。
您可以使用计算
属性使您的注入(inject)
具有反应性。检查Provide / Inject: Working with Reactivity部分。
- 注入(inject)就像
props
和readonly
。
您可以更改子组件中注入(inject)的值,但更改不会发送到父组件。
检查提供的Vue SFC Playground Example澄清一下。
解决方案是使用自定义商店或Vuex/Pinia .
这是更新后的SFC Playground .
Message2 仅在 GrandChild、nub 中更新,但不在父应用程序中更新。
关于typescript - 提供/注入(inject)和更改注入(inject)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75733472/