观察 Vue 3 全局变量的变化

时间:2021-06-02 20:22:27

标签: vue.js vuejs3 vitejs

我在 main.ts 文件中设置了一个提供程序:

app.provide('currentPage','test1')

然后将其注入到组件 Home.vue 中:

inject: ['currentPage'],

然后我可以使用 {{ currentPage }} 更新它并在该组件中显示它而不会出现问题。

但我希望另一个组件 DeepNestedComponent.vue 能够对其进行编辑,并且 Home.vue 能够了解更改。

当我在 DeepNestedComponent.vue 中注入相同的提供程序时,我可以在组件中进行编辑和显示,但是 Home.vue 不知道更改并且 {{ currentPage }} 仍然显示“test1”。< /p>

我该怎么做?

2 个答案:

答案 0 :(得分:1)

此模式仅设计用于将某些属性从祖父组件传递给孙组件,您的案例需要基于 Vuex 的可共享状态或可组合函数,让我们基于第二种方法构建解决方案:

定义可组合函数:

usePagination.ts

import {  ref } from "vue";

const currentPage=ref('test')

export default function usePagination(){

  function setCurrentPage(val:string){
      currentPage.value=val;
 }

return {currentPage, setCurrentPage}
}

DeepNestedComponent.vue

import usePagination from './usePagination'
...
setup(){
  const { setCurrentPage} =usePagination();

  // then use setCurrentPage to update the page

}

Home.vue :

import usePagination from './usePagination'
...
setup(){
  const { currentPage} =usePagination();

  // now you could receive the changes made in the other component.
  return {
       currentPage // expose it to the template 
   }
}

答案 1 :(得分:0)

provide/inject 严格用于在层次结构中传递某些东西(有点类似于依赖注入)。它不会改变/修饰给定的目标。这意味着如果您提供字符串,它将作为字符串被消耗(注入),并且字符串本身不是反应性。< /p>

如果你希望它是反应式的,你需要提供一个反应式对象或引用:

<script>
  import {defineComponent, ref, provide} from 'vue';
  import Parent from "./Parent.vue";
  
  export default defineComponent({
    setup (){
      const msg = ref("Hello World");
      provide("message", msg);
      return {msg};
    },
    
    components: {
      Parent
    }
  });
</script>

complete example

相关问题