Vue ContentEditable (Jumping Cursor Problem)

Unfortunately, you cannot customize the styling of the text in a <textarea>. Therefore, you need to use a <div contenteditable=”true” @input=”handleInput”>. When the user types inside the <div>, the handleInput method will be called which will store the text in the vuex store. This approach will allow the user to type into the <div>.

// store
export const state = () => ({
sampleText: ''
});
setCreatePostText(state,payload){
state.sampleText = payload
},
<!-- component/template -->
<div id="text-area-div" contenteditable="true" @input="handleInput">{{sampleText}}</div>
// methods
handleInput(e) {
this.$store.commit('setSampleText', e.target.innerText)
},
// computed
sampleText(){
return this.$store.state.networkModule.sampleText
}

However, if you rerender this text in a different component with a <div contenteditable=”true”>, when the user types into the new div, the cursor will jump to the start of the div because the DOM is rerendering every time the user enters new text. To prevent this behavior, we can store the text in an array instead of an object. According to the Vue docs (https://vuejs.org/v2/guide/reactivity.html), if we change the data of an array in the store by setting the index, Vuex does not detect the change. As such, this approach will prevent the DOM from rerendering. Note, if you want Vue to rerender when making a change to an array by setting the index, you must use Vue.set()

// store
export const state = () => ({
sampleText: ['']
});
setCreatePostText(state,payload){
state.sampleText[0] = payload
},
<!-- component/template -->
<div id="text-area-div" contenteditable="true" @input="handleInput">{{sampleText}}</div>
// methods
handleInput(e) {
this.$store.commit('setSampleText', e.target.innerText)
},
// computed
sampleText(){
return this.$store.state.networkModule.sampleText[0]
}

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store