this.$refs与this.$emit()
this.$refs
父组件向子组件通信,可以调用子组件里的属性和方法
示例
父组件
<template> <child ref="msg" /> </template> <script> import child from "./child.vue"; export default { name: "parent", components: {child}, mounted(){ // 通过ref定位组件并调用组件的方法 this.$refs.msg.setMessage("我是子组件") } } </script>
子组件
<template> <h1>{{msg}}</h1> </template> <script> export default { name: "", data(){ return { msg: "" } }, methods: { setMessage(msg){ this.msg = msg; } } } </script>
this.$emit()
子组件向父组件通信
使用方式
vm.$emit( event, arg )
示例
父组件
<template> <!-- 通过绑定子组件定义的getMessage事件获取信息 --> <child @getMessage="showMessage" /> </template> <script> import child from "./child.vue"; export default { name: "parent", components: {child}, methods: { showMessage(msg){ console.log(msg) } } } </script>
子组件
<template> <h1>{{msg}}</h1> </template> <script> export default { name: "", data(){ return { msg: "hello" } }, methods: { getMessage(){ this.$emit("getMessage", this.msg) } } } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)