父组件
<template> <hello-world/> <button @click="changeMessage">按钮</button> </template> <script setup lang="ts"> import HelloWorld from "./components/HelloWorld.vue"; import {provide, ref} from "vue"; const messages = ref("消息提示") provide("messages",messages) function changeMessage() { messages.value = "改变消息" + Math.random() console.log(messages.value) } </script> <style scoped lang="scss"> </style>
子组件
<script setup lang="ts"> import {inject, ref} from 'vue' import LittlePage from "./little-page.vue"; const messages = inject("messages") defineProps<{ msg: string }>() const count = ref(0) </script> <template> {{messages}} <little-page/> </template> <style scoped> .read-the-docs { color: #888; } </style>
孙组件
<template> <h1>{{message}}</h1> </template> <script setup lang="ts"> import {inject} from "vue"; const message = inject("messages") </script> <style scoped lang="less"> </style>
标签:vue,const,provide,messages,inject,vue3,import From: https://www.cnblogs.com/hhcome/p/17661377.html