网站首页 > 教程文章 正文
在 Vue 3 + Vue Router 里,<RouterView /> 本质上就是一个 动态渲染子组件的插槽。如果你想让子页面调用父组件的方法,或者获取父组件的数据,有几种方式。
1 使用props 传递数据/函数
父组件
<template>
<div>
<h1>父组件</h1>
<RouterView :parentMessage="message" :parentFn="handleClick" />
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const message = ref('Hello from parent')
const handleClick = () => {
alert('父组件方法被调用了!')
}
</script>
子页面(通过 RouterView 渲染的组件)
<template>
<div>
<p>父组件消息: {{ parentMessage }}</p>
<button @click="parentFn">调用父组件函数</button>
</div>
</template>
<script setup lang="ts">
defineProps<{
parentMessage: string
parentFn: () => void
}>()
</script>
这样父组件变量和函数就可以传递给 <RouterView /> 渲染的页面了。
2 使用provide / inject(适合跨多层组件传递)
父组件
import { provide, ref } from 'vue'
const message = ref('Hello from parent')
const handleClick = () => alert('父组件函数')
provide('parentMessage', message)
provide('parentFn', handleClick)
子页面
import { inject } from 'vue'
const parentMessage = inject('parentMessage') as Ref<string>
const parentFn = inject('parentFn') as () => void
3 使用Pinia / 全局状态管理
如果你父子组件比较复杂,或者父组件不是直接父级,推荐用 Pinia(或 Vuex)存储父组件变量和函数:
// store.ts
import { defineStore } from 'pinia'
export const useParentStore = defineStore('parent', {
state: () => ({ message: 'Hello', counter: 0 }),
actions: {
handleClick() { this.counter++ }
}
})
父组件
const store = useParentStore()
子页面
const store = useParentStore()
console.log(store.message)
store.handleClick()
总结
方法 | 适合场景 | 优缺点 |
props + <RouterView> | 父组件直接传给当前路由页面 | 简单、清晰、类型安全 |
provide / inject | 父组件和子组件多层嵌套,不想逐层传 props | 灵活,但可读性差 |
Pinia / Vuex | 跨多个页面共享状态或方法 | 全局状态,容易管理大型应用 |
猜你喜欢
- 2025-08-26 前端分享-VueUse着实是有东西的_vue.use是什么
- 2025-08-26 Vue CLI相关配置_vue—cli
- 2025-08-26 【推荐】一款轻量简洁优雅的 Vue3 中后台管理模板,开源免费可商用
- 2025-08-26 vue3使用vue-i18n国际化_vue 国际化
- 2025-08-26 超惊艳 Vue3.x 组件库Na"ive UI_文笔超惊艳的高质量小说古言
- 2025-08-26 vue:组件中之间的传值_vue组件之间的传值方式
- 2025-08-26 Vue前端开发——组件篇_vue 前端组件
- 2025-08-26 超好看 vue2.x 音频播放器组件Vue-APlayer
- 2025-08-26 Vuex与SpreadJS施展“组合拳”,实现大屏展示应用的交互增强
- 2025-08-26 别再用React/Vue了!14KB的htmx如何让你的网站性能提升300%
- 最近发表
- 标签列表
-
- location.href (44)
- document.ready (36)
- git checkout -b (34)
- 跃点数 (35)
- 阿里云镜像地址 (33)
- qt qmessagebox (36)
- mybatis plus page (35)
- vue @scroll (38)
- 堆栈区别 (33)
- 什么是容器 (33)
- sha1 md5 (33)
- navicat导出数据 (34)
- 阿里云acp考试 (33)
- 阿里云 nacos (34)
- redhat官网下载镜像 (36)
- srs服务器 (33)
- pico开发者 (33)
- https的端口号 (34)
- vscode更改主题 (35)
- 阿里云资源池 (34)
- os.path.join (33)
- redis aof rdb 区别 (33)
- 302跳转 (33)
- http method (35)
- js array splice (33)