依赖注入
Provide (提供)
父组件通过 provide
提供数据或方法。
<script setup>
import { provide } from 'vue'provide(/* 注入名 */ 'message', /* 值 */ 'hello!')
</script>
Inject (注入)
子组件通过 inject
接收父组件提供的数据或方法。
<script setup>
import { inject } from 'vue'
// 通过注入名来查找值
const message = inject('message')
</script>
和响应式数据配合使用
// 父组件
<template><div><h1>父组件</h1><ChildComponent /><button @click="updateMessage">更新消息</button></div>
</template><script setup>
import { ref, provide } from 'vue'
import ChildComponent from '../components/ChildComponent.vue'
const message = ref('这是来自父组件的消息')
provide('messageValue', message)
const updateMessage = () => {message.value = '新的消息'
}
</script>
// 子组件
<template><div><h2>子组件</h2><p>{{ injectedMessage }}</p></div>
</template><script setup>
import { ref, inject } from 'vue'
// 注入响应式数据
const injectedMessage = inject('messageValue')
</script>
组件间的 v-modal
v-model
可以在组件上使用以实现数据双向绑定。defineModel()
工具函数用于简化自定义组件中 v-model
的实现,不需要再手动定义 props
和 emit
事件。
<template><div><h1>父组件</h1><p>输入的值:{{ inputValue }}</p><input type="text" v-model="inputValue" /><ChildComponent v-model="inputValue" /></div>
</template><script setup>
import { ref } from 'vue'
import ChildComponent from '../components/ChildComponent.vue'
const inputValue = ref('')
</script>
<template><div><h2>子组件</h2><input v-model="model" /></div>
</template><script setup>
import { ref, defineModel } from 'vue'// 使用 defineModel 创建双向绑定
const model = defineModel('inputValue')
</script>
多个 v-model
绑定
//父组件
<template><div><h1>父组件</h1><p>输入的值:{{ inputValue }}</p><input type="text" v-model="inputValue" />// 可以创建多个双向绑定// 父组件通过 v-model:inputValue 和 v-model:modelValue 分别绑定 inputValue 和 modelValue。<ChildComponentv-model:inputValue="inputValue"v-model:modelValue="modelValue"/><p>子组件的值:{{ modelValue }}</p></div>
</template><script setup>
import { ref } from 'vue'
import ChildComponent from '../components/ChildComponent.vue'
const inputValue = ref('')
const modelValue = ref('')
</script>
<template><div><h2>子组件</h2><input v-model="model" /><input type="text" v-model="modelValue" /></div>
</template><script setup>
import { ref, defineModel } from 'vue'// 子组件通过 defineModel('inputValue') 和 defineModel('modelValue') 创建多个双向绑定。
const model = defineModel('inputValue')
const modelValue = defineModel('modelValue')
</script>