vue中的事件觸發(fā)(emit)及監(jiān)聽(on)問題
vue事件觸發(fā)(emit)及監(jiān)聽(on)
每個 vue 實例都實現了事件接口
- 1.使用 $on(eventName,callback) 監(jiān)聽事件
- 2.使用 $emit(eventName,[…args]) 觸發(fā)事件
$emit 和 $on 必須都在實例上進行觸發(fā)和監(jiān)聽。
// on監(jiān)聽emit觸發(fā)的事件
created:function(){
? ? this.$on('emitFn',(arg)=> {
? ? ? ? ? console.log('on監(jiān)聽參數====',arg) ?//['string',false,{name:'vue'}]
? ? ? })
? },
? methods:{
? ? emit () {
? ? ?? ?// $emit 事件觸發(fā) ?參數是多個不同的數據類型時 用數組傳遞
? ? ? ? ?this.$emit('emitFn',['string',false,{name:'vue'}])
? ? ? ? ?
? ? ? ? ?// 監(jiān)聽多個emit事件,將事件名用數組形式寫 ?['emitFn1','emitFn2'];
? ? ? ? ? this.$emit(['emitFn1','emitFn2'],'arg1')
? ? ? }
? }案例
通過在父級組件中,拿到子組件的實例進行派發(fā)事件,然而在子組件中事先進行好派好事件監(jiān)聽的準備,接收到一一對應的事件進行一個回調,同樣也可以稱之為封裝組件向父組件暴露的接口。
vue emit事件無法觸發(fā)問題
在父組件中定義事件監(jiān)聽,會出現無法觸發(fā)對應的事件函數,在下面的代碼中,我想通過v-on:event_1=“handle”, 想監(jiān)聽子組件中的event_1事件,但盡管事件發(fā)生了, 但還是觸發(fā)不了,這個問題在于v-on:event_1="handle"的位置,需要放在 <my-template :users=“users” v-on:event_1=“handle” ></my-template> 中。
<body>
<div id='app' v-on:event_1="handle1">
<my-template :users="users"></my-template>
</div>
</body>
<script>
Vue.component('my-template', {
data: function () {
return {
test:"hello"
}
},
props: ["users"],
template: `
<div>
<ul>
<li v-for="item in users" :key="item.id">
<div>
<label>name:</label>
{{item.name}}
<label>content:</label>
{{item.content}}
<label>time:</label>
{{item.time}}
<input type="button" value="remove" @click="remove(item.id)"></input>
<input type="button" value="通知" @click="$emit('event_1',this)"></input>
</div>
</li>
</ul>
</div>
`,
methods:{
remove(id){
console.log(id);
for(let i = 0; i<this.users.length;++i){
if(this.users[i].id == id){
this.users.splice(i,1);
break;
}
}
},
notice(id){
console.log("notice", id);
},
handle(e){
console.log("son handle",e)
}
}
})
var vm = new Vue({
el: '#app',
data: {
posts: [
{ id: 1, title: 'My journey with Vue' },
{ id: 2, title: 'Blogging with Vue' },
{ id: 3, title: 'Why Vue is so fun' }
],
postFontSize: 1,
searchText: 'hello',
users:[
{
name:"zhangsan",
id:'1',
time:new Date().getUTCDate(),
content:"白日依山盡,黃河入海流"
},
{
name:"lisi",
id:'2',
time:new Date().getUTCDate(),
content:"會當凌絕頂,一覽眾山小"
},
{
name:"wangwu",
id:'3',
time:new Date().getUTCDate(),
content:"大漠孤煙直,長河落日圓"
}
]
},
methods:{
handle1(e){
console.log("event 事件觸發(fā),參數為:",e);
}
}
})
</script>
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

