当前位置: 首页> 教育> 高考 > 荆楚网_邢台市人民医院_谷歌浏览器app下载_b2b网站排名

荆楚网_邢台市人民医院_谷歌浏览器app下载_b2b网站排名

时间:2025/7/10 9:02:01来源:https://blog.csdn.net/m0_57036170/article/details/146203545 浏览次数:1次
荆楚网_邢台市人民医院_谷歌浏览器app下载_b2b网站排名

依赖注入

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 的实现,不需要再手动定义 propsemit 事件。

<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>
关键字:荆楚网_邢台市人民医院_谷歌浏览器app下载_b2b网站排名

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: