I\'m using Vue.js with Nuxt in SSR, I would like when I highlight some text to get this text and perform an action on it.
I found a way to do that with
The select
event is only supported by input-like elements. If you want to get the selected text within regular elements, simply listen to the mouseup
event. The mouseup event should call a function where you simply call window.getSelection().toString()
to retrieve the selected text.
In the example below, we bind the mouseup
listener to the document
, and perform additional filtering within the event handler so that only an element of interest (in this case, this.$refs.target
) will trigger the callback that gets the selection:
new Vue({
el: '#app',
mounted() {
document.addEventListener('mouseup', event => {
if (event.target === this.$refs.target || event.target.contains(this.$refs.target))
this.testFunction();
});
},
methods: {
testFunction() {
console.log(window.getSelection().toString());
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input @select="testFunction" value="Text to select" />
<p ref="target">Lorem ipsum dolor sit amet</p>
</div>
Update: Based on your answer, you will either want to update what the event.target
is compared against (e.g. if you don't want any selection to trigger testFunction()
), or leave the if
conditional out completely:
document.addEventListener('mouseup', event => {
this.testFunction1();
});
I'm unclear on whether you want to react to a selection inside the input or elsewhere in the document. Assuming inside the input:
mouseup
event.$event
.getSelection()
doesn't work on input values, so use selectionStart
and selectionEnd
to get the selection.new Vue({
el: '#app',
methods: {
logSelectionWithinInput(e) {
var selection = e.target.value.substring(
e.target.selectionStart,
e.target.selectionEnd
);
console.log(selection);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input @mouseup="logSelectionWithinInput($event)" value="Text to select" />
</div>