vue 提供注入状态更改

  • 本文关键字:状态 注入 vue vue.js
  • 更新时间 :
  • 英文 :


我想通过 offer 更改消息的值,但它没有任何效果,我想知道我哪里出错了?

我查看了提供注入事件,但无法弄清楚。

App.vue

<script>
import Child from './Child.vue'
export default {
components: { Child },
data(){
message:false
},
provide() {
return {
fullMessage: this.message
}
}
}
</script>
<template>
<Child />
</template>

Child.vue

<script>
import GrandChild from './GrandChild.vue'
export default {
components: {
GrandChild
}
}
</script>
<template>
<GrandChild />
</template>

孙子

<script>
export default {
inject: ['fullMessage'],
methods:{
handleStatus(){
this.fullMessage = !this.fullMessage
}
}
}
</script>
<template>
<p>essage to grand child: {{ fullMessage }}</p>
<button @click="handleStatus">
Status Change
</button>
</template>

您可以使用 ref 或 reactive 来更改提供的值:

const { ref, provide, inject } = Vue
const app = Vue.createApp({
setup() {
const fullMessage = ref(false)
provide('fullMessage', fullMessage)
}
})
app.component('child', {
template: `
<grand-child></grand-child>
`
})
app.component('grandChild', {
template: `
<p>message to grand child: {{ fullMessage }}</p>
<button @click="handleStatus">
Status Change
</button>
`,
setup() {
const fullMessage = inject('fullMessage')
return {
fullMessage,
handleStatus: () => fullMessage.value = !fullMessage.value
}
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<child></child>
</div>

要在选项 API 中执行此操作,您需要在 vue 版本为 <3.3 时在main中添加app.config.unwrapInjectedRef = true,并且还使用computed提供计算属性

import {computed} from "vue"
provide(){
return {
fullMessage: computed({
get: () => this.message,
set: (value) => {this.message = value}
})
}
}

最新更新