Pyreal
Pyreal

Reputation: 517

Target the textarea of a child component to copy to clipboard

I have a working function which targets a textarea and copies the content to a clipboard. It works great when targeting a textarea directly.

I need the same functionality targeting the textarea within a child component(s). I can't figure out how to target that specific area within each component.

Working example:

<div class="media-label col-md-12">Product Title:</div>

<textarea 
  class="col-md-6 col-md-offset-3" 
  v-model="productTitle" 
  id="productTitle"
></textarea>

<button 
  type="button" 
  class="btn btn-info"
  data-copytarget="#productTitle" 
  v-on:click="copyTextArea"
>
  Copy Title To Clipboard
</button>

The copy function:

 copyTextArea(e) {
   var targetElement = e.target;
   var copiedTarget = targetElement.dataset.copytarget;
   var element = document.querySelector(copiedTarget);
   element.select();
   document.execCommand('copy');
 },

Component setup I'm having issues with:

<ExampleComponent
  title="Title" 
  input-type="textarea"
  v-model="productTitle" 
  id="productTitle" 
></ExampleComponent>

<button 
  type="button" 
  class="btn btn-info"
  copytarget="#productTitle" 
  v-on:click="copyTextArea"
>
  Copy Title To Clipboard
</button>

<ExampleComponent
  title="Description" 
  input-type="textarea"
  v-model="productTitle" 
  id="productTitle"
></ExampleComponent>

<button 
  type="button" 
  class="btn btn-info"
  copytarget="#productTitle" 
  v-on:click="copyTextArea"
>
  Copy Title To Clipboard
</button>

Upvotes: 3

Views: 8243

Answers (1)

thanksd
thanksd

Reputation: 55644

Use a ref on the textarea and then reference the element directly in the copyTextArea method:

new Vue({
  el: '#app',
  methods: {
    copyTextArea() {
      this.$refs.text.select();
      document.execCommand('copy');
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <div>Product Title:</div>
  <textarea ref="text"></textarea>
  <button @click="copyTextArea">
    Copy Title To Clipboard
  </button>
</div>

Upvotes: 9

Related Questions