首先有两个组件:
父组件:App.vue
子组件:ComponentForOne.vue
<template> <img alt="Vue logo" src="./assets/logo.png"> <!-- 下面使用组件:组件标签名 --> <ComponentForOne @onEvent="getCpData" :title="msg" :age="age" :arr="arr"/> </template> <script> // 此处引入组件 import 组件标签名 from 组件所在位置 import ComponentForOne from './components/ComponentForOne.vue'; export default { name: 'App', components: { // 挂载组件 ComponentForOne }, methods:{ getCpData(data){ this.arr[2]=data } }, data(){ return{ msg:"App中的msg", age:12, arr:["1","2","3"] } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
<template> <h1>Here is ComponentForOne!!</h1> <p>{{title}}</p> <p>age = {{age}}</p> <ul style="background-color:aqua"> <li v-for="(item,index) in arr" :key="index">{{item}}</li> </ul> <p>将数据从自定义组件传递给App.vue</p> <button @click="sendApp">给app.vue</button> </template> <script> // 导出 export default{ // 当前组件的名称,在导入使用时需要用到 name:"ComponentForOne", data(){ return{ msg:"给App.vue" } }, methods:{ sendApp(){ // 参数1:字符串,理论上是自定义字符串,但是需要有一定意义 // 参数2:传递的数据 this.$emit("onEvent",this.msg) } }, // 通过props在组件间传递参数 props:{ title:{ type:String, default:"" }, age:{ type:Number, default:20 }, arr:{ type:Array, // 数组和对象必须使用函数返回 default:function(){ return [] } } } } </script> <!-- scoped :如果添加了此属性,表示只在当前组件中生效 --> <style scoped> h1{ color: aqua; } </style>
首先在子组件创建一个按钮和对应的点击事件 sendApp ,然后将点击事件写入methods:
事件内容就是 this.$emit("onEvent",this.msg),给父组件提供一个名为 onEvent 的事件该事件包含值 msg
然后父组件使用这个事件,并使用这个事件中的值:
看看效果:
点击之前:
点击之后:
那么值就成功地从子组件传递到了父组件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)