思路
實(shí)現(xiàn)該組件有兩個(gè)思路,一個(gè)使用v-model進(jìn)行雙向綁定,一個(gè)是使用prop的.sync修飾符、父子組件通信。
1.v-model形式
v-model的實(shí)現(xiàn)需要在自定義組件中自定義一個(gè)inputvalue值,因?yàn)関ue中的父子組件傳遞機(jī)制問(wèn)題,在組件中直接修改props注入的key字段時(shí),vue會(huì)給出錯(cuò)誤。子組件中定義inputvalue字段,用于子組件中input元素的值的雙向綁定,子組件中的input數(shù)據(jù)綁定可以使用v-model,也可以使用實(shí)現(xiàn)v-model的原理語(yǔ)法糖,下面兩種方式都可作為子組件中的數(shù)據(jù)綁定。
<input type="password" v-model="inputvalue"/><input type="password" :value="inputvalue" @input="inputvalue=$event.target.value"/>
關(guān)于v-model的實(shí)現(xiàn)可查看其他關(guān)于v-model的實(shí)現(xiàn)文章。
最后實(shí)現(xiàn)的子組件文件如下,這里的顯示隱藏的點(diǎn)擊使用的是文字,實(shí)際使用時(shí)可使用對(duì)應(yīng)的icon字體圖標(biāo),并設(shè)定一定的樣式。
<template><div> <input :type='show?"text":"password"' :value="inputvalue" @input="inputvalue=$event.target.value" :placeholder='placeholder'/> <i :title="show?'隱藏密碼':'顯示密碼'" @click="changePass" style="cursor:pointer;">{{show?'隱藏':'顯示'}}</i></div></template> <script>export default { props: { value: { default: "", type: String }, placeholder: { default: "", type: String }, }, data(){ return{ inputvalue:"", show:false,//密碼顯示或隱藏的Boolean,默認(rèn)false,密碼不顯示 } }, watch:{ inputvalue(news,olds){ this.$emit("input",news); } }, mounted(){ this.inputvalue=this.value; }, methods:{ changePass(){ this.show=!this.show; } }}</script><style></style>父組件引用方式如下
<input-password v-model="value"></input-password>
因?yàn)檫@里實(shí)現(xiàn)的v-model的綁定方式,而v-model的實(shí)現(xiàn)就是監(jiān)聽(tīng)的input事件,則當(dāng)inputvalue改變時(shí),則向父組件發(fā)出input事件,父組件使用v-model監(jiān)聽(tīng)input事件,修改父組件中的value值,此處實(shí)現(xiàn)了雙向綁定,同時(shí)在顯示和隱藏的i標(biāo)簽上綁定事件,點(diǎn)擊i標(biāo)簽時(shí)改變show的值,通過(guò)判斷show的值動(dòng)態(tài)改變input的type,實(shí)現(xiàn)密碼的顯示和隱藏。
2。.sync修飾符
.sync修飾符的實(shí)現(xiàn)與v-model的實(shí)現(xiàn)方式相同,唯一不同的是watch監(jiān)聽(tīng)inputvalue變化時(shí)向父組件發(fā)出的事件修改為 "update:value" ,修改后inputvalue的監(jiān)聽(tīng)函數(shù)如下
inputvalue(news,olds){ this.$emit("update:value",news); },父組件引用方式
<input-password :value.sync="value"></input-password>
寫(xiě)到最后
其實(shí)兩種方式的實(shí)現(xiàn)最主要需要的還是父子組件之間的傳值,使用emit,vuex,或自定義倉(cāng)庫(kù)等都可實(shí)現(xiàn)父子組件中的傳值,監(jiān)聽(tīng)inputvalue修改時(shí)可以同時(shí)使用兩種emit發(fā)送,可同時(shí)支持兩種方式。
新聞熱點(diǎn)
疑難解答
圖片精選