How can I use the event @select to select some text from a paragraph in Vue.js?

前端 未结 2 832
深忆病人
深忆病人 2021-01-28 06:10

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

相关标签:
2条回答
  • 2021-01-28 06:45

    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();
    });
    
    0 讨论(0)
  • 2021-01-28 07:04

    I'm unclear on whether you want to react to a selection inside the input or elsewhere in the document. Assuming inside the input:

    • Listen to mouseup event.
    • Pass the event itself with $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>

    0 讨论(0)
提交回复
热议问题