Vue父组件与子组件传递事件/调用事件

不念不忘少年蓝@ 2022-04-25 04:40 395阅读 0赞

转载文章出处

Vue父组件与子组件传递事件/调用事件

1、Vue父组件向子组件传递事件/调用事件

  1. <div id="app">
  2. <hello list="list" ref="child"></hello>
  3. <br />
  4. <button v-on:click="myclick">调用子组件中的方法</button>
  5. </div>
  6. <template id="myT"></template>
  7. <script>
  8. Vue.component('hello', {
  9. template: '#myT',
  10. methods: {
  11. clickme: function () {
  12. alert("dd");
  13. }
  14. }
  15. });
  16. var app=new Vue({
  17. el: '#app',
  18. methods: {
  19. myclick: function () {
  20. this.$refs.child.clickme();
  21. }
  22. }
  23. });
  24. </script>

如果传递参数,可以使用 props数据

2.子组件调用父组件事件

  1. <div id="app">
  2. <hello list="list" v-on:wzhclick="wzhclick"></hello>
  3. </div>
  4. <template id="myT">
  5. <button v-on:click="childclick">调用父组件的方法</button>
  6. </template>
  7. <script>
  8. Vue.component('hello', {
  9. template: '#myT',
  10. methods: {
  11. childclick: function () {
  12. this.$emit('wzhclick', {a:1,b:2});
  13. }
  14. }
  15. });
  16. var app=new Vue({
  17. el: '#app',
  18. methods: {
  19. wzhclick: function (data) {
  20. alert("我是父组件,参数"+data.a+";"+data.b);
  21. },
  22. }
  23. });
  24. </script>

子组件通过this.$emit()派发事件,父组件利用v-on对事件进行监听,实现参数的传递

3.两平等组件间的调用

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" />
  5. <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
  6. <link href="~/Content/css/font-awesome.min.css" rel="stylesheet" />
  7. <script src="~/Content/js/jquery-1.8.2.min.js"></script>
  8. <script src="~/Content/js/bootstrap.min.js"></script>
  9. <script src="~/Scripts/vue.min.js"> </script>
  10. <script src="~/Scripts/axios.min.js"></script>
  11. <style>
  12. </style>
  13. <div id="app">
  14. <wzh></wzh>
  15. <zl></zl>
  16. </div>
  17. <script>
  18. var Event = new Vue();//事件调度器
  19. Vue.component('wzh', {
  20. template: '<div>wzh:<input v-on:keyup="isay" v-model="msg">{
  21. {msg}}</div>',
  22. data: function () {
  23. return {
  24. msg:''
  25. }
  26. },
  27. methods: {
  28. isay: function () {
  29. Event.$emit("wzhsay", this.msg);
  30. }
  31. }
  32. });
  33. Vue.component('zl', {
  34. template:'<div>wzh说了:{
  35. {wzhmsg}}</div>',
  36. data: function () {
  37. return {
  38. wzhmsg:'',
  39. }
  40. },
  41. mounted: function () {
  42. var me = this;
  43. Event.$on("wzhsay", function (data) {
  44. me.wzhmsg = data;
  45. });
  46. }
  47. });
  48. var app=new Vue({
  49. el: '#app',
  50. });
  51. </script>

new一个调度器来Event来完成,在mounted中监听事件,另一个组件中调用Event.$emit来调用此事件完成调度。

发表评论

表情:
评论列表 (有 0 条评论,395人围观)

还没有评论,来说两句吧...

相关阅读