vue实现文本选取
文本选取的基本实现
使用Vue实现文本选取功能可以通过结合原生JavaScript的Selection API完成。以下是一个基础示例,通过指令或方法监听文本选择事件:
<template>
<div @mouseup="handleTextSelection" ref="selectableText">
{{ content }}
</div>
<p>已选文本: {{ selectedText }}</p>
</template>
<script>
export default {
data() {
return {
content: '这是一段可供选择的示例文本...',
selectedText: ''
}
},
methods: {
handleTextSelection() {
const selection = window.getSelection();
this.selectedText = selection.toString().trim();
}
}
}
</script>
自定义指令实现
创建自定义指令v-select可以复用文本选择逻辑:
Vue.directive('select', {
bind(el, binding) {
el.addEventListener('mouseup', () => {
const selection = window.getSelection();
const selectedText = selection.toString().trim();
if (selectedText) {
binding.value(selectedText);
}
});
}
});
使用方式:
<div v-select="handleSelectedText">{{ content }}</div>
高亮选中文本
通过Range API实现选中文本的高亮显示:

methods: {
highlightSelection() {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.className = 'highlight';
range.surroundContents(span);
selection.removeAllRanges();
}
}
CSS样式:
.highlight {
background-color: yellow;
color: black;
}
跨浏览器兼容处理
不同浏览器对Selection API的实现存在差异,需要做兼容处理:

getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
文本选择事件扩展
添加防抖和选择边界检测:
handleTextSelection: _.debounce(function() {
const selection = window.getSelection();
if (!selection.isCollapsed) {
const range = selection.getRangeAt(0);
if (this.$refs.selectableText.contains(range.commonAncestorContainer)) {
this.selectedText = selection.toString();
}
}
}, 300)
服务端交互示例
将选中文本发送至后端:
methods: {
async sendSelectionToServer() {
const text = this.getSelectedText();
if (!text) return;
try {
await axios.post('/api/selected-text', { text });
this.$toast.success('文本已保存');
} catch (error) {
console.error(error);
}
}
}
移动端触摸支持
针对移动设备添加touch事件支持:
mounted() {
this.$refs.selectableText.addEventListener('touchend', this.handleTouchSelection);
},
methods: {
handleTouchSelection() {
setTimeout(() => {
const selection = window.getSelection();
this.selectedText = selection.toString();
}, 100);
}
}






