组合 API 全局状态未更新 DOM

Composition API global state is not updating the DOM

使用合成来获得全局状态 API。

但可组合项状态的更改不会反映到组件的 DOM。

useProducts.js

import { reactive, toRefs} from "vue";

export default function useProducts() {
  // STATE
  const state = reactive({
    title: "old title"
  });
  // METHODS
  const changeTitle = function (title) {
    state.title = title;
    console.log(state.title, "the state changed here");
  }

  return {
    ...toRefs(state),
    changeTitle,
  };
}

catalog.vue 产品标题我已经上钩了,显示的是初始状态

<template>
  <q-page class="full-height full-width">
    <h4>Products {{ title }}</h4>  <!-- old title -->
  </q-page>
</template>

<script>
  ...
  setup() {
    const { title } = useProducts();
    return {
      title,
    };
  },
 ...
</script>

app.vue 让我们在 3 秒后将标题从“旧标题”更改为“新标题”

  setup() {
    const { changeTitle } = useProducts();
    onMounted(() => {
      setTimeout(() => {
        changeTitle("New title");
      }, 3000); // we want to change the title for the entire App
    });
  },

当应用程序初始化时,catalog.vue 显示产品状态的正确 title。但在 三秒后 标题没有改变。

catalog.vue 中的标题仍然是“旧标题”,即使在 app.vue[= 中调用 changeTitle() 37=]

我的错误,反应状态要在useProducts()

外声明
import { reactive, toRefs} from "vue";
// STATE
const state = reactive({
  title: "old title"
});
export default function useProducts() {
  // METHODS
  const changeTitle =  (title) =>{
    state.title = title;
    console.log(state.title, "the state changed here");
  }
  return {
    ...toRefs(state),
    changeTitle,
  };
}