最近在開(kāi)發(fā)自己的富文本編輯器插件,在開(kāi)發(fā)中遇到了很多問(wèn)題其中我覺(jué)得比較好的問(wèn)題就是在你定義的插件中實(shí)現(xiàn)雙向綁定。就好像input中v-model的功能類(lèi)似。
v-model語(yǔ)法:
在vue中我們實(shí)現(xiàn)表單的雙向綁定時(shí)代碼一般時(shí)這樣寫(xiě)的:
<input type="text" v-model="value" style="line-height: 30px;">data () { return { value: '222' }}可以通過(guò)這樣的方式實(shí)現(xiàn)value的值和輸入框中的值雙向綁定了。
事實(shí)上v-model只是一個(gè)語(yǔ)法糖,他的真正實(shí)現(xiàn)是這樣的:
<input type="text" :value="value" @input="value=$event.target.value">
以上代碼分幾個(gè)步驟:
1.將輸入框的值綁定到變量上,這個(gè)是單向綁定,意味著改變變量的值可以改變輸入框的值,但是改變輸入框的值不能改變變量的值
2.監(jiān)聽(tīng)input事件(input輸入框都有該事件,當(dāng)輸入內(nèi)容時(shí)自動(dòng)觸發(fā)該事件),當(dāng)輸入框輸入內(nèi)容就單向改變變量的值了
自定義編輯器雙向綁定
這個(gè)是插件的寫(xiě)法:content是雙向綁定的值 height是指編輯器的高度
<editor v-model="content" :height="editorHeight"></editor>
插件vue的寫(xiě)法:
<div v-bind:style="{height: height}" class="editor-box" ref="editor" contenteditable v-html="contentHtml" @input="changeText"></div>在div中設(shè)置contenteditable屬性時(shí)把div設(shè)置成可編輯的輸入框,v-html是給編輯器單向綁定變量contentHtml值,input方法獲取編輯器的內(nèi)容并且返回給父元素的input方法:
changeText () { const htmlString = this.$refs.editor.innerHTML this.$emit('input', htmlString) },其他問(wèn)題:
光是這樣是不能夠解決問(wèn)題的,編輯器你會(huì)出現(xiàn)每次輸入的時(shí)候都會(huì)跳到開(kāi)頭位置:怎么解決呢?不多說(shuō)上代碼:
props: { value: { type: String, default: '' }, height: { type: String, default: 'auto' } },data () { return { // 編輯器內(nèi)容 contentHtml: this.value || this.value === 0 ? this.value : '<div><br></div>', // 是否在編譯 isLocked: true, // 光標(biāo)位置 lastEditRange: null } }, watch: { value (val) { if (!this.isLocked) { this.contentHtml = this.value; } } }寫(xiě)到這里大家應(yīng)該一頭霧水這樣寫(xiě)有什么用:因?yàn)檫€少了一些代碼:
<div v-bind:style="{height: height}" class="editor-box" ref="editor" contenteditable v-html="contentHtml" @input="changeText" @focus="focusEditor" @blur="blurEditor"></div> // 編輯器失去焦點(diǎn) blurEditor (event) { this.isLocked = false }, // 編輯器獲得焦點(diǎn) focusEditor (event) { this.isLocked = true },需要給插件添加兩個(gè)方法判斷編輯器是否正在編輯內(nèi)容,如果正在編輯中父組件綁定的值不讓他重新渲染子組件,這樣編輯器中的內(nèi)容就不會(huì)重新賦值了,這樣光標(biāo)就不會(huì)每次都跑到前面去了。
小小的總結(jié)一下:
•v-bind只能實(shí)現(xiàn)單向綁定
•v-model(v-bind+觸發(fā)的input事件)實(shí)現(xiàn)雙向綁定
總結(jié)
以上所述是小編給大家介紹的vue插件實(shí)現(xiàn)v-model功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注