1. 程式人生 > >可編輯文字

可編輯文字

寫一個可編輯文字的小元件

<template>
  <span class="edit-div" v-html="innerText" :contenteditable="canEdit" @focus="isLocked = true" @blur="isLocked = false" @input="changeText" :placeholder="placeholder" style="line-height:40px;cursor:pointer;color:teal;">
  </span>
</template>
<script type="text/ecmascript-6">
export default {
  name: "editSpan",
  props: {
    value: {
      type: String,
      default: ""
    },
    placeholder: {
      type: String,
      default: "請輸入"
    },
    canEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      innerText: this.value,
      isLocked: false
    };
  },
  watch: {
    value() {
      if (!this.isLocked) {
        this.innerText = this.value;
      }
    }
  },
  methods: {
    changeText() {
      this.$emit("input", this.$el.innerHTML);
    }
  }
};
</script>
<style lang="scss" rel="stylesheet/scss">
.edit-div {
  height: 100%;
  word-break: break-all;
  user-select: text;
  white-space: pre-wrap;
  &[contenteditable="true"] {
    user-modify: read-write-plaintext-only;
    &:empty:before {
      content: attr(placeholder);
      display: inline-block;
      color: #ccc;
    }
  }
}
</style>

在需要編輯文字的地方引用這個元件

<edit-span :value="item.message" @input="val=>item.message=val"></edit-span>

即可