🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 子传父 ***** >>子传父通过$emit('自定义事件名称',需要传递的变量)完成 ***** > 1. 使用$emit()触发自定义事件,触发方法就可以带上变量 this.$emit(自定义事件名称, 需要传递给父的值) > 2. 找到子组件标签<my-con> ,在这个标签上增加一个自定义事件, 通过@自定义事件="响应事件的方法" > 3. 在父组件上实现相应方法,方法接受的参数,就是触发自定义事件传递的值 <br> ``` <div id="app"> <my-con1></my-con1> </div> <template id="temp"> <div> <p>我是1111{{str}} {{str1}}</p> //在子组件上绑定自定义事件 @自定义事件名 = ‘响应事件的方法’ <my-con2 @getstr='newStr'></my-con2> </div> </template> <template id="temp1"> <div> <p>我是2222{{str}}</p> //触发子组件上的方法(里面是自定义事件) <button @click='getStr'>按钮</button> </div> </template> <script> new Vue({ el: '#app', components: { 'MyCon1': { template: '#temp', data: function () { return { str: '+++1111str', str1: '' } }, methods: { newStr(c) { this.str1 = c; } }, components: { 'MyCon2': { template: '#temp1', data: function () { return { str: '+++22222str' } }, methods: { getStr() { //自定义事件,传递需要传递的变量 //事件名不能有大写 this.$emit('getstr', this.str); } } } } }, }, }) </script> ```