typescript - 提供/注入(inject)和更改注入(inject)变量

标签 typescript vue.js

我在组件中提供变量,并在其子组件中注入(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.

有什么办法可以解决这个问题吗?

最佳答案

  1. 注入(inject)默认情况下不是 react 性的。

您可以使用计算属性使您的注入(inject)具有反应性。检查Provide / Inject: ​​Working with Reactivity部分。

  • 注入(inject)就像 propsreadonly
  • 您可以更改子组件中注入(inject)的值,但更改不会发送到父组件。

    检查提供的Vue SFC Playground Example澄清一下。

    解决方案是使用自定义商店或Vuex/Pinia .

    这是更新后的SFC Playground .

    Message2 仅在 GrandChild、nub 中更新,但不在父应用程序中更新。

    关于typescript - 提供/注入(inject)和更改注入(inject)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75733472/

    相关文章:

    javascript - 您可以将元素传递给 Vue 模板中的函数吗?

    css - VueJS背景图像url找不到路径

    vue.js - Vuetify 数据表 : Fetch data when expanding a row

    Vue.js:用户单击按钮时加载模板(或 div)?

    typescript - ng2-bootstrap 分页和 bootstrap 表集成错误

    javascript - 在vuex中创建常量变量?

    typescript - 带有Typescript Vuex对象的Vue Vuex未知类型

    reactjs - React/Typescript - 至少需要 '3' 参数,但 JSX 工厂 'React.createElement' 最多提供 '2' 。 TS622

    typescript - 是否有 CDK 或 CloudFormation 构造来导入整个 DNS 区域传输?

    node.js - 如何为具有构造函数(例如 imap)的复杂外部 commonjs 模块编写 TypeScript 声明文件?