元素contenteditable属性可以控制元素是否可以输入编辑。div加上这个属性就可以作为一个高度自动撑开的输入框。
在Vue中创建全局组件使用:
1、创建输入框组件MyInput:
<template> <div :id="Id" class="my-input" :contenteditable="!disabled" @input="changeText" v-html="innerText"></div> </template> <script> export default{ name: "MyInput", props: { value:"", disabled:{}, }, data: function() { return { innerText: "", Id:"", } }, mounted(){ this.init(); }, methods: { init(){ // console.log(this.value) this.Id = this.$getGuid();//生成一个不重复的随机Id this.innerText = this.value; }, changeText() { let text = $(`#${this.Id}`).html(); this.$emit(‘input‘, text); } } } </script> <style scoped> .my-input { width: 100%; font-size: 13px; line-height: 20px; outline: none; border: 0; padding: 0 10px; text-align: left; } .my-input:empty::before { content: "输入..."; color: #999; } .my-input:focus::before { content: none; } </style>
2、全局注册组件
import MyInput from "./components/common/myInput"
Vue.component(‘my-input‘,MyInput);
3、引用该组件
<my-input :disabled="forbidden" v-model="content"></my-input>