vue子组件使用自定义事件向父组件传递数据

使用v-on绑定自定义事件可以让子组件向父组件传递数据,用到了this.$emit(‘自定义的事件名称',传递给父组件的数据)

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<parent-component></parent-component>
</div>
<template id="parent-component">
<div>
 <p>总数是{{total}}</p>
 <child-component @increment="incrementTotal"></child-component>
 <!--@increment是子组件this.$emit('increment'自定义的事件用来告诉父组件自己干了什么事
 然后会触发父子间incrementTotal的方法来更新父组件的内容)-->
</div>
</template>
<template id="child-component">
 <button @click="increment()">{{mycounter}}</button>
</template>
<script>
 var child=Vue.extend({
  template:"#child-component",
  data:function () {
   return {
    mycounter:0
   }
  },
  methods:{
   increment:function(){
    this.mycounter=10;
    this.$emit("increment",this.mycounter);//把this.mycounter传递给父组件
   }
  }
 })
 var parent=Vue.extend({
  data:function () {
   return {
    total:0
   }
  },
  methods:{
   incrementTotal:function(newValue){
    this.total+=newValue;
   }
  },
  template:"#parent-component",
  components:{
   'child-component':child
  }
 })
 var vm=new Vue({
  el:"#app",
  components:{
   'parent-component':parent
  }
 })
</script>
</body>
</html>

@increment是子组件this.$emit('increment'自定义的事件,newValue)用来告诉父组件自己干了什么事

同时还可以传递新的数据给父组件

然后会触发父子间incrementTotal的方法来更新父组件的内容)。

这里需要注意几个点:

1.

图中红色圈中的部分是对应的,子组件在自己的methods方法里面写自己的事件实现,然后再父组件里面写字组件时给子组件绑定上methods方法里面的

事件名称,要一一对应

这里自定义事件里面的要写父组件的方法名,父组件里面定义该方法。

父组件里面的方法可以接收子组件this.$emit('increment',this.mycounter);传递过来的数值:this.mycounter,

到父组件的方法里面就是newValue参数,这样就实现了子组件向父组件传递数据

以上所述是小编给大家介绍的vue子组件使用自定义事件向父组件传递数据,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!