본문 바로가기
Vue.js

[Vue] textarea에 개행마다, 높이 늘어나고, shift+enter 개행이고, enter하면 서브밋하는 코드

by devebucks 2023. 2. 19.
728x90
<script>
export default {
  name: 'ResizableTextarea',
  props: {
    value: {
      type: String,
      default: '',
    },
  },
  methods: {
    updateValue(event) {
      if (event.shiftKey) return;
      if (event.keyCode === 13) {
        this.$emit('enter');
        event.preventDefault();
        setTimeout(() => {
          this.resize();
        });
        return;
      }
      this.resize();
      this.$emit('input', event.target.value);
    },
    resize() {
      const targetTextArea = this.$refs.remarksTextArea;
      targetTextArea.style.height = '1px';
      targetTextArea.style.height = targetTextArea.scrollHeight + 'px';
      this.$emit('resize', targetTextArea.scrollHeight);
    },
  },
};
</script>
<template>
  <textarea
    type="text"
    :value="value"
    :ref="`remarksTextArea`"
    placeholder="메세지를 입력하세요"
    @keydown="updateValue($event)"
  ></textarea>
</template>

<style lang="scss" scoped="scss">
textarea {
  width: 100%;
  border-radius: 4px;
  padding: 8px;
  height: 38px;
  resize: none;
  overflow-y: hidden;
  min-height: 38px;
  max-height: 80px;
}
</style>
728x90

댓글