我在我的
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}
}
DeepNestedComponent.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
}
}
在 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>
当我想为我的网站配色方案设置全局变量时,从“Vue3 reactive components on globalProperties”找到了这个解决方案
provide/inject
严格意味着 passing 层次结构中的某些东西(有点类似于依赖注入)。它不会改变/修饰给定的目标。这意味着如果您提供一个 string,它将作为一个 string 被消耗(注入),并且一个字符串本身不是 reactive。
如果你希望它是响应式的,你需要提供一个响应式对象或引用:
<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>