Vue父组件与子组件传递事件/调用事件
1、Vue父组件向子组件传递事件/调用事件<div id="app"><hello list="list" ref="child"></hello><br /><button v-on:click="my
·
1、Vue父组件向子组件传递事件/调用事件
<div id="app"> <hello list="list" ref="child"></hello> <br /> <button v-on:click="myclick">调用子组件中的方法</button> </div> <template id="myT"></template> <script> Vue.component('hello', { template: '#myT', methods: { clickme: function () { alert("dd"); } } }); var app=new Vue({ el: '#app', methods: { myclick: function () { this.$refs.child.clickme(); } } }); </script>
如果传递参数,可以使用 props数据
2.子组件调用父组件事件
<div id="app"> <hello list="list" v-on:wzhclick="wzhclick"></hello> </div> <template id="myT"> <button v-on:click="childclick">调用父组件的方法</button> </template> <script> Vue.component('hello', { template: '#myT', methods: { childclick: function () { this.$emit('wzhclick', {a:1,b:2}); } } }); var app=new Vue({ el: '#app', methods: { wzhclick: function (data) { alert("我是父组件,参数"+data.a+";"+data.b); }, } }); </script>
子组件通过this.$emit()派发事件,父组件利用v-on对事件进行监听,实现参数的传递
3.两平等组件间的调用
@{ ViewBag.Title = "Index"; } <link href="~/Content/css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/css/font-awesome.min.css" rel="stylesheet" /> <script src="~/Content/js/jquery-1.8.2.min.js"></script> <script src="~/Content/js/bootstrap.min.js"></script> <script src="~/Scripts/vue.min.js"> </script> <script src="~/Scripts/axios.min.js"></script> <style> </style> <div id="app"> <wzh></wzh> <zl></zl> </div> <script> var Event = new Vue();//事件调度器 Vue.component('wzh', { template: '<div>wzh:<input v-on:keyup="isay" v-model="msg">{{msg}}</div>', data: function () { return { msg:'' } }, methods: { isay: function () { Event.$emit("wzhsay", this.msg); } } }); Vue.component('zl', { template:'<div>wzh说了:{{wzhmsg}}</div>', data: function () { return { wzhmsg:'', } }, mounted: function () { var me = this; Event.$on("wzhsay", function (data) { me.wzhmsg = data; }); } }); var app=new Vue({ el: '#app', }); </script>
new一个调度器来Event来完成,在mounted中监听事件,另一个组件中调用Event.$emit来调用此事件完成调度。
更多推荐
已为社区贡献2条内容
所有评论(0)