今天來看一個很簡單的需求。
需求描述:在輸入框光標處,插入指定的內容。
效果如下:
實現思路:剛開始還在想怎么獲取光標的位置,但是發現所做的項目是基于vue3+antd組件,那么不簡單了嘛,只要調用textarea組件的blur事件,就能獲取到光標最后出現的位置!
示例代碼:
<template>插入選項:<a-tagv-for="item in insertList":key="item"color="green"@click="handleTagClick(item)">{{ item }}</a-tag><a-textareav-model:value="inputValue":autoSize="{ minRows: 4 }"@blur="handleBlur"style="margin-top: 5px;"></a-textarea>
</template><script lang="ts" setup>
import { ref } from "vue";const inputValue = ref(); // 輸入的內容
const cursorPos = ref(); // 光標的位置
const insertList = ["內容1", "tag", "標簽2", "test", 'XXXX'];const handleBlur = (e: any) => {cursorPos.value = e.srcElement.selectionStart;
};const handleTagClick = (tag: string) => {if (inputValue.value === undefined) { // 輸入內容為空,直接插入inputValue.value = tag;} else {const start = inputValue.value.substring(0, cursorPos.value || 0),end = inputValue.value.substring(cursorPos.value || 0);inputValue.value = `${start}${tag}${end}`;}
};
</script>
存在的問題:多次點擊插入選項時,都只會往光標最后一次出現的位置,插入內容,算不算問題,這個就看具體需求啦~