vue实现文字选中
Vue 实现文字选中功能
在 Vue 中实现文字选中功能,可以通过监听鼠标事件或使用浏览器原生 API 完成。以下是几种常见方法:
使用 mouseup 事件监听选中文本
通过监听 mouseup 事件获取用户选中的文本内容:

<template>
<div @mouseup="handleTextSelection">
<p>这是一段可选中文字的内容示例。</p>
</div>
</template>
<script>
export default {
methods: {
handleTextSelection() {
const selectedText = window.getSelection().toString();
if (selectedText) {
console.log('选中的文字:', selectedText);
// 其他处理逻辑
}
}
}
}
</script>
通过指令封装选中逻辑
封装一个自定义指令,实现选中文字的通用逻辑:

// 全局指令
Vue.directive('select-text', {
bind(el, binding) {
el.addEventListener('mouseup', () => {
const selection = window.getSelection();
const selectedText = selection.toString();
if (selectedText && binding.value) {
binding.value(selectedText);
}
});
}
});
// 使用方式
<template>
<div v-select-text="handleSelectedText">
<p>指令方式实现的文字选中功能</p>
</div>
</template>
<script>
export default {
methods: {
handleSelectedText(text) {
console.log('选中文字:', text);
}
}
}
</script>
高亮选中文本
结合 Range API 实现选中文本的高亮效果:
<template>
<div @mouseup="highlightSelection">
<p>选中这段文字会高亮显示</p>
</div>
</template>
<script>
export default {
methods: {
highlightSelection() {
const selection = window.getSelection();
if (!selection.isCollapsed) {
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.style.backgroundColor = 'yellow';
range.surroundContents(span);
selection.removeAllRanges();
}
}
}
}
</script>
跨组件通信选中内容
如果需要将选中内容传递到其他组件,可以使用 Vuex 或事件总线:
// 使用事件总线
const eventBus = new Vue();
// 选中文本时触发事件
methods: {
emitSelectedText() {
const text = window.getSelection().toString();
if (text) {
eventBus.$emit('text-selected', text);
}
}
}
// 其他组件监听
created() {
eventBus.$on('text-selected', text => {
console.log('接收到的选中文本:', text);
});
}
注意事项
getSelection()返回的是用户当前选中的任意内容,可能超出当前组件范围- 高亮操作会修改 DOM 结构,可能影响后续的选中行为
- 移动端需要额外处理
touch事件 - 富文本编辑器等复杂场景建议使用专用库(如
rangy)
以上方法可根据实际需求组合使用,实现更复杂的文字选中交互功能。






