我在main.ts文件中设置了一个提供程序:
app.provide('currentPage','test1')
然后将其注入组件Home.vue中。
inject: ['currentPage'],
然后,我可以更新它并在该组件中显示它,而不用使用{{ currentPage }}。
但我希望另一个组件DeepNestedComponent.vue能够编辑它,并希望Home.vue知道更改。
当我在DeepNestedComponent.vue中注入相同的提供程序时,我可以在组件中编辑和显示,但是Home.vue不知道更改,{{ currentPage }}仍然显示‘test1 1’。
我怎么能这么做?
发布于 2021-06-02 21:11:15
此模式仅用于将一些属性从祖父母组件传递给孙辈组件,您的情况需要基于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
}
}发布于 2022-04-28 02:38:20
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>当我想为我的网站配色方案设置一个全局变量时,从"Vue3反应元件在globalProperties上“找到了这个解决方案。
发布于 2021-06-04 07:40:58
provide/inject的意思是严格意义上的将传递到层次结构中(类似于依赖注入)。它不会改变/装饰给定的目标。这意味着如果您提供了一个字符串,它将被作为一个字符串使用(注入),而一个字符串本身并不是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>https://stackoverflow.com/questions/67812058
复制相似问题