vue子组件使用自定义事件向父组件传递数据
2019/6/27 20:56:20
本文主要是介绍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子组件使用自定义事件向父组件传递数据,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!
这篇关于vue子组件使用自定义事件向父组件传递数据的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-30React Native常用组件-点击组件
- 2024-05-30uniapp+vue3+uv-ui手机端后台OA管理模板
- 2024-05-29Python网络爬虫的时候json=就是让你少写个json.dumps()
- 2024-05-27React Native常用组件-展示组件
- 2024-05-27React Native常用组件-列表组件
- 2024-05-09vue3开发前端表单缓存自定义指令,移动端h5必备插件
- 2024-05-09React Hooks在class组件中的使用方式
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist