Vue 2 contentEditable with v-model

后端 未结 6 1334
别跟我提以往
别跟我提以往 2020-12-05 14:01

I\'m trying to make a text editor similar to Medium. I\'m using a content editable paragraph tag and store each item in an array and render each with v-for. However, I\'m ha

6条回答
  •  执念已碎
    2020-12-05 14:39

    I thought I might contribute because I don't feel that the given solutions are the most elegant or concise to clearly answer what is needed or they don't provide the best use of Vue. Some get close, but ultimately need a bit of tweaking to really be effective. First note, the

    paragraph does not support v-model. The content is in the innerHTML and is only added using {{content}} inside the element slot. That content is not edited after inserting. You can give it initial content but every time you refresh the content, the content editing cursor gets reset to the front (not a natural typing experience). This leads to my final solution:

    ...
    

    {{ content }}

    ... props: { content: {type:String,defalut:"fill content"}, manage: { type: Boolean, default: false }, ... data: function() { return { bioContent: this.content ... methods: { handleInput: function(e) { this.bioContent = e.target.innerHTML.replace(/(?:^(?: )+)|(?:(?: )+$)/g, ''); }, ...

    My suggestion is, put in an initial static content value into the

    slot, then have a @input trigger to update a second active content variable with what is put into the innerHTML from the contenteditable action. You will also want to trim off the end HTML format whitespace created by the

    element, otherwise you will get a gross string at the end if you have a space.

    If there is another, more effective solution, I am not aware of it but I am welcome to suggestions. This is what I have used for my code and I am confident that it will be performant and suit my needs.

提交回复
热议问题