观察Vue 3全局变量的变化



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

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

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

inject: ['currentPage'],

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

但我希望另一个组件DeepNestedComponent.vue能够编辑它,并且Home.vue能够意识到更改。

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

我该怎么做?

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

定义可组合函数:

使用分页.ts

import {  ref } from "vue";
const currentPage=ref('test')
export default function usePagination(){
function setCurrentPage(val:string){
currentPage.value=val;
}
return {currentPage, setCurrentPage}
}

深度嵌套组件.vue

import usePagination from './usePagination'
...
setup(){
const { setCurrentPage} =usePagination();
// then use setCurrentPage to update the page
}

主页.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严格用于在层次结构中传递内容(有点类似于依赖注入(。它不会变异/修饰给定的目标。这意味着,如果您提供字符串,它将作为被消耗(注入(,并且字符串本身不是反应性

如果你想让它是被动的,你需要提供一个被动的对象或参考:

<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>

完整的示例

vue3反应/可监视全局变量

在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>

从";globalProperties上的Vue3反应性组件";当我想为我的网站配色方案设置一个全局变量时

根类中的css变量对于设置配色方案也很好