我有一个工作函数,它针对textarea并将内容复制到剪贴板.它直接针对textarea时效果很好.
我需要针对子组件中的textarea提供相同的功能.我无法弄清楚如何定位每个组件中的特定区域.
工作范例:
<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>
Run Code Online (Sandbox Code Playgroud)
复制功能:
copyTextArea(e) {
var targetElement = e.target;
var copiedTarget = targetElement.dataset.copytarget;
var element = document.querySelector(copiedTarget);
element.select();
document.execCommand('copy');
},
Run Code Online (Sandbox Code Playgroud)
组件设置我遇到了以下问题:
<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>
Run Code Online (Sandbox Code Playgroud)
ref在textarea上使用a ,然后直接在copyTextArea方法中引用元素:
new Vue({
el: '#app',
methods: {
copyTextArea() {
this.$refs.text.select();
document.execCommand('copy');
}
},
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)