观察 Vue 3 全局变量的变化

Watch Vue 3 global variable for changes

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

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

然后在组件中注入Home.vue:

inject: ['currentPage'],

然后我可以使用 {{ currentPage }}.

更新它并在该组件中毫无问题地显示它

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

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

我该怎么做?

此模式仅用于将一些 属性 从祖父组件传递给孙子组件,您的案例需要基于 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 
   }
}

provide/inject 严格用于 传递 层次结构中的某些东西(有点类似于依赖注入)。它不 mutate/decorate 给定的目标。这意味着如果您提供 string,它将作为 string 被使用(注入),并且字符串本身不是 无反应.

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

<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

vue3 Reactive/Watchable 全局变量

在main.js

import { ref } from 'vue';
app.config.globalProperties.$currentPage = ref("Page 1");

观察某个文件中的变量 (Home.vue)

<template>
    <div>{{ currentPage }}</div>
</template>
<script>
export default {
  name: "App",
  data(){
     return {
         currentPage: "test1"
     }
  },
  mounted() {
    this.updateCurrentPage()
  },
  watch: {
    '$currentPage.value':{
      handler: function () {
          this.updateCurrentPage()
      }, deep: true }
  },
  methods: {
    updateCurrentPage(){
      this.currentPage = this.$currentPage.value
    }
  }
}
</script>

在另一个(DeepNestedComponent.vue)中更改变量

<template>
   <div>
      <button @click="changePage()">changePage</button>
   </div>
</template>
<script>
export default {
  name: 'DeepNestedComponent',
  data(){
    return {
      pageCount: 0
    }
  },
  methods:{
    changePage(){
      this.pageCount    = this.pageCount + 1
      const pageValue   = `Page ${this.pageCount}`
      this.$currentPage = pageValue
    }
  }
}
</script>

当我想为我的网站配色方案设置一个全局变量时,从 找到了这个解决方案