vuejs:单击时将标签内容复制到剪贴板而不创建功能

发布于 2025-02-13 10:15:33 字数 150 浏览 1 评论 0原文

如何在不使用自己的功能的情况下将HTML标签的内容复制到剪贴板?

<div @click="navigator.clipboard.writeText(this)">Hello {{ name }}!</div>

How to copy the content of an html tag to clipboard without using own function?

<div @click="navigator.clipboard.writeText(this)">Hello {{ name }}!</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不必了 2025-02-20 10:15:33

根据 > ,通用代码无法假设访问特定于平台的API,因此,如果您的代码直接使用仅浏览器的全球范围,例如window文档,他们会丢弃错误。因此,常见的方法是懒洋洋地访问仅客户端的生命周期挂钩,例如已安装

实时演示

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
    browserApi: null
  },
  mounted() {
    this.browserApi = navigator
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div ref="elText" @click="browserApi.clipboard.writeText($refs.elText.innerText)">Hello {{ name }}!</div>
</div>

As per the document, Universal code cannot assume access to platform-specific APIs, so if your code directly uses browser-only globals like window or document, they will throw errors. Hence, the common approach is to lazily access them inside client-only lifecycle hooks such as mounted.

Live Demo :

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
    browserApi: null
  },
  mounted() {
    this.browserApi = navigator
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div ref="elText" @click="browserApi.clipboard.writeText($refs.elText.innerText)">Hello {{ name }}!</div>
</div>

迷爱 2025-02-20 10:15:33

我认为在VUE3中,没有“丑陋”解决方案是不可能的,请参阅此处的灵感。但是我认为,最清洁的方法是只用其中一行代码创建一种方法。

I think in Vue3 that is not possible without 'ugly' solutions, see here for inspiration. But I think the cleanest way is to just create a method with that one line of code in it.

玻璃人 2025-02-20 10:15:33

更适合可读性

vue;

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
  },
  methods {
    copyPageUrl(){
        navigator.clipboard.writeText($refs.elText.innerText)
    },
  }
})

html;

<div id="app">
  <div ref="elText" @click="copyPageUrl">Hello {{ name }}!</div>
</div>

better for readability

Vue;

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
  },
  methods {
    copyPageUrl(){
        navigator.clipboard.writeText($refs.elText.innerText)
    },
  }
})

Html;

<div id="app">
  <div ref="elText" @click="copyPageUrl">Hello {{ name }}!</div>
</div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文