Vue在組件上使用v-model
自定義事件也可以用于創建支持 v-model 的自定義輸入組件,記住:
<input v-model="searchText">
等價于:
<input
:value="searchText"
@input="searchText = $event.target.value"
>
當用在組件上時,v-model 則會這樣:
<custom-input
:value="searchText"
@input="searchText = $event"
></custom-input>
上面用
$event接收子組件用$emit()向上傳遞過來的資料
為了讓它正常作業,這個組件內的 <input> 必須:
- 將其
valueattribute 系結到一個名叫value的 prop 上 - 在其
input事件被觸發時,將新的值通過自定義的input事件拋出
寫成代碼之后是這樣的:
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
>
`
})
現在 v-model 就應該可以在這個組件上完美地作業起來了:
<custom-input v-model="searchText"></custom-input>
以下是更簡化代碼,我發現不用寫 :value這個屬性也能正常的實作資料的雙向系結
<div id="app">
<input-com v-model="username"></input-com>
<h1>{{ username }}</h1>
</div>
Vue.component("input-com",{
// 當用戶輸入資料的時候把value值傳遞給父組件
template: `<input @input="$emit('input',$event.target.value)" />`,
})
var app = new Vue({
el: "#app",
data: {
username: ""
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/200647.html
標籤:其他
上一篇:2020-11-01
