如何在 vue 3 中创建全局状态?

Rup*_*iri 3 javascript vue.js vuejs3

我已经创建了一个反应值,但我希望它从整个应用程序中改变。

为了创建我所拥有的反应状态,src/store/index.js其中包含

// ** src/store/index.js

export function useTimer() {
  const timer = ref(false);

  const toggleTimer = () => {
    if (timer.value == false) {
      timer.value = true;
    } else {
      timer.value = false;
    }
  };

  return { timer, toggleTimer };
}
Run Code Online (Sandbox Code Playgroud)

我在组件中使用这些值

// ** src/app.vue 

<template>
  <Scores/>
  <button @click="switchtimer()">switch at app</button>
</template>

<script>
import { isRef } from "vue";
import { useTimer } from "./store";
import Scores from "./components/Scores.vue";

export default {
  components: {
    Scores
  },
  setup() {

    const { timer, toggleTimer } = useTimer();

    function switchtimer() {
      console.log(isRef(timer));    // true
      toggleTimer();

    }
    return { switchtimer };
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)
// ** src/components/Scores.vue

<template>
  <button @click="switchtimer()">switch at scores</button>
  <p>{{ timer }}</p>
</template>

<script>
import { isRef } from "vue";
import { useTimer } from "../store";

export default {
  name: "Scores",
  setup() {

    const { timer, toggleTimer } = useTimer();

    function switchtimer() {
      console.log(isRef(timer));    // true
      toggleTimer();

    }
    return { timer, switchtimer };
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

Scores.vue 作为组件导入到 app.vue 中。即使我在本描述中犯了任何错误,应用程序中也不存在导入问题。这个错误可能是在发布此内容时重写时发生的。

switch at scores按下按钮时,计时器会在分数组件中切换,但switch at app按下按钮时,计时器不会在分数组件中切换。

我希望将计时器作为全局状态,这样当从 app.vue 更改它时,更改后的值也会显示在 Scores.vue 中。

Dan*_*iel 5

修复方法很简单,你需要让 ref 变量持久化

// ** src/store/index.js

const timer = ref(false); // <=== outside of function scope

export function useTimer() {
  const toggleTimer = () => {
    if (timer.value == false) {
      timer.value = true;
    } else {
      timer.value = false;
    }
  };

  return { timer, toggleTimer };
}
Run Code Online (Sandbox Code Playgroud)

通过将其移出函数作用域,您将不再timer在每次调用该函数时创建一个新变量,而是引用同一个变量,就像单例一样。