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

前端 未结 2 833
深忆病人
深忆病人 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());
        }
      }
    });
    
    

    Lorem ipsum dolor sit amet

    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();
    });
    

提交回复
热议问题