provide() 和 inject() 可以实现嵌套组件之间的数据传递。
这两个函数只能在 setup() 函数中使用。
父级组件中使用 provide() 函数向下传递数据。
子级组件中使用 inject() 获取上层传递过来的数据。
<template> <a :href="href" :style="{fontSize:title.size}" target="_blank">{{title.text}}</a> </template> <script lang="ts"> import { ref, reactive, inject } from "vue"; export default{ setup(props) { let href = inject('href', "http://www.163.com"); let title = inject('title',{ text : "连接标题", size : "18px" }); return {href, title}; }, } </script>
<template> <my-link /> <button @click="changeToAli">切换到阿里云</button> </template> <script lang="ts"> import MyLink from "./components/MyLink.vue"; import { reactive, provide, ref } from "vue"; export default{ props:{ name : { type:String, default:'grace' } }, setup(props) { const href = ref("https://www.graceui.com"); let title = reactive({ text : 'Grace', size:'58px' }); // provide 前先生命响应式变量 provide('href', href); provide('title', title); const changeToAli = ()=>{ href.value = "https://www.aliyun.com/"; title.text = '阿里云'; } return {changeToAli}; }, components:{ MyLink } } </script> <style> </style>
|
{{comment.u_nickname}}
{{comment.u_nickname}} @ {{comment.comments_reply_uname}}
{{comment.comments_date}}
点赞 ({{comment.comments_like_count}})
  回复 ({{comment.comments_reply_count}})
|