子组件向父组件传值的步骤(按时间先后):
- 在父组件模板中,在子组件标签上使用v-on自定义事件绑定父组件中的函数
2, 在子组件对象中适当的位置使用this.$emit发射(触发)这个自定义事件, 把数据传入自定义事件中
this.$emit(“myevent”, this.childName)
3, 在父组件中的事件函数中,通过参数获取子组件发送的数据, 并给父组件数据更新修改
getData(data){ this.fatherData.name = data }
<body> <script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script> <div id='myApp'> 父组件: {{fatherData.name}} <hr> 子组件: <my-com @myevent="getData">在子组件标签上使用v-on绑定自定义事件, 调用父组件中的事件函数</my-com> </div> <!-- 组件模板 --> <template id='myTem'> <div> <input type="text" v-model="childName"> <button @click="change">修改</button> </div> </template> <script> Vue.component('myCom', { template: '#myTem', data(){ return{ childName: "" } }, methods:{ change(){ // 把childName传给父组件,修改父组件的name // 在子组件发射一个自定义事件, 第一个参数是自定义事件名, 不能有大写, 第二个参数是发送的数据 this.$emit("myevent", this.childName) } } }) new Vue({ el: '#myApp', data: { fatherData: { name: "父组件名字" } }, methods: { getData(data){ // 在父组件的事件函数中接收子组件发送的数据, 并由父组件来更新父组件自己的数据 this.fatherData.name = data } } }) </script></body>