Vue 中自定義事件內容分發
- 1.什么是內容分發
- 2.如何實作內容分發
1.什么是內容分發
純屬說概念的話會過于呆板并且十分抽象不好理解,可以簡單的將內容分發理解為在Vue中定義的函式通過傳遞的方式使得組件通過this.$emit(‘自定義事件名’,param…)進行呼叫,下面小編舉例說明
現在有如下需求:
資料是通過for回圈遍歷出來的,需要對每個元素點擊洗掉的時候,該對應元素會被洗掉

2.如何實作內容分發
1.雙向系結自定義資料以及展示資料
Vue.component("todo",{
template: '<div>\
<slot name="todo-tip"></slot>\
<ul>\
<slot name="todo-item"></slot>\
</ul>\
</div>'
})
Vue.component("todo-tip",{
props: ['title'],
template:'<div>{{title}}</div>'
})
Vue.component("todo-item",{
props: ['it'],
template: '<li>{{it}} <button>洗掉</button></li>'
})
var vm = new Vue({
el: "#app",
data: {
message: ['A','B','C','D','E','F','G'],
title: '迪迦羊肉串'
}
})
展示資料:
<div id="app">
<todo>
<todo-tip slot="todo-tip" :title="title"></todo-tip>
<todo-item slot="todo-item" :it="msg" v-for="(msg,index) in message" ></todo-item>
</todo>
</div>
2.為vm中系結洗掉元素函式
var vm = new Vue({
...
methods: {
rmItem: function(dex) {
console.log("當前洗掉的是"+this.message[dex])
this.message.splice(dex,1)
}
}
})
3.將函式系結到組件上
<todo-item v-on:myclick="rmItem(index)"></todo-item>
4.在組件中創建函式并且呼叫
template: '<li>{{it}} <button @click="todo_rm">洗掉</button></li>', //在button中系結函式
methods: {
todo_rm: function(){
this.$emit('myclick') // 自定義函式呼叫
}
}
5.點擊洗掉按鈕

整體來說其實還是比較繞的,所以在寫自定義事件之前,要理清楚思路,便會豁然開朗了~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/267051.html
標籤:其他
