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來調用此事件完成調度。