vue子组件中怎么通过自定义事件向父组件传递数据

这篇文章将为大家详细讲解有关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.

vue子组件中怎么通过自定义事件向父组件传递数据

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

事件名称,要一一对应

vue子组件中怎么通过自定义事件向父组件传递数据

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

vue子组件中怎么通过自定义事件向父组件传递数据

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

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

关于vue子组件中怎么通过自定义事件向父组件传递数据就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。