colinox/FED-Notes

Vue实现DIV可编辑v-model绑定效果

Opened this issue · 0 comments

Vue实现DIV可编辑v-model绑定效果

父组件:

<template>
    <taskTitle v-model="title" />
</template>

<script>
    export default{
        data(){
            return {
                title: '这是一个标题'
            }
        },
        watch: {
            title(newData,oldData){
                if(oldData != undefined){
                    editTitle(newData);
                }
            }
        },
        methods: {
            editTitle(value){
                console.log('更新内容为:'+ value);
            }
        }
    }
</script>

子组件:

<template>
    <div class="edit-div" v-html="innerText" :contenteditable="canEdit" @focus="isLocked = true" @blur="isLocked = false" @input="changeText"></div>
</template>
<script>
    export default{
        props: {
            value: {
                type: String,
                default: ''
            },
            canEdit: {
                type: Boolean,
                default: true
            }
        },
        data(){
            return {
                innerText: this.value,
                isLocked: false
            }
        },
        watch: {
            'value'(){
                if (!this.isLocked || !this.innerText) {
                    this.innerText = this.value;
                }
            }
        },
        methods: {
            changeText(){
                this.$emit('input', this.$el.innerHTML);
            }
        }
    }
</script>
<style lang="scss" rel="stylesheet/scss">
    .edit-div {
        width: 100%;
        height: 100%;
        overflow: auto;
        word-break: break-all;
        outline: none;
        user-select: text;
        white-space: pre-wrap;
        text-align: left;
    }
    .edit-div[contenteditable=true]{
        user-modify: read-write-plaintext-only;
    }
    .edit-div[contenteditable=true]:empty:before {
        content: attr(placeholder);
        display: block;
        color: #ccc;
    }
</style>