GithubHelp home page GithubHelp logo

inndy / vue-clipboard2 Goto Github PK

View Code? Open in Web Editor NEW
1.8K 1.8K 242.0 561 KB

A simple vue2 binding to clipboard.js

Home Page: https://vue-clipboard2.inndy.tw/

License: MIT License

JavaScript 99.41% Makefile 0.59%
clipboard copy vue vue2 vuejs vuejs2

vue-clipboard2's Introduction

vue-clipboard2

A simple vuejs 2 binding for clipboard.js

DEPRECATED

I'm so grateful for all of you who have used and supported this project over the years. It's been a fun ride, but it's time to say goodbye.

As of 2023, Vue2 is on its way out and the Clipboard API is now pretty much everywhere.

So you don't need this plugin anymore, just use navigator.clipboard.writeText('text') and you're good to go. Thanks again for everything and happy coding!

Install

npm install --save vue-clipboard2 or use dist/vue-clipboard.min.js without webpack

Usage

For vue-cli user:

import Vue from 'vue'
import VueClipboard from 'vue-clipboard2'

Vue.use(VueClipboard)

For standalone usage:

<script src="vue.min.js"></script>
<!-- must place this line after vue.js -->
<script src="dist/vue-clipboard.min.js"></script>

I want to copy texts without a specific button!

Yes, you can do it by using our new method: this.$copyText. See sample2, where we replace the clipboard directives with a v-on directive.

Modern browsers have some limitations like that you can't use window.open without a user interaction. So there's the same restriction on copying things! Test it before you use it. Make sure you are not using this method inside any async method.

Before using this feature, read: this issue and this page first.

It doesn't work with bootstrap modals

See clipboardjs document and this pull request, container option is available like this:

let container = this.$refs.container
this.$copyText("Text to copy", container)

Or you can let vue-clipboard2 set container to current element by doing this:

import Vue from 'vue'
import VueClipboard from 'vue-clipboard2'

VueClipboard.config.autoSetContainer = true // add this line
Vue.use(VueClipboard)

Sample

<div id="app"></div>

<template id="t">
  <div class="container">
    <input type="text" v-model="message">
    <button type="button"
      v-clipboard:copy="message"
      v-clipboard:success="onCopy"
      v-clipboard:error="onError">Copy!</button>
  </div>
</template>

<script>
new Vue({
  el: '#app',
  template: '#t',
  data: function () {
    return {
      message: 'Copy These Text'
    }
  },
  methods: {
    onCopy: function (e) {
      alert('You just copied: ' + e.text)
    },
    onError: function (e) {
      alert('Failed to copy texts')
    }
  }
})
</script>

Sample 2

<div id="app"></div>

  <template id="t">
    <div class="container">
    <input type="text" v-model="message">
    <button type="button" @click="doCopy">Copy!</button>
    </div>
  </template>

  <script>
  new Vue({
    el: '#app',
    template: '#t',
    data: function () {
      return {
        message: 'Copy These Text'
      }
    },
    methods: {
      doCopy: function () {
        this.$copyText(this.message).then(function (e) {
          alert('Copied')
          console.log(e)
        }, function (e) {
          alert('Can not copy')
          console.log(e)
        })
      }
    }
  })
  </script>

You can use your Vue instance vm.$el to get DOM elements via the usual traversal methods, e.g.:

this.$el.children[1].children[2].textContent

This will allow you to access the rendered content of your components, rather than the components themselves.

Contribution

PRs welcome, and issues as well! If you want any feature that we don't have currently, please fire an issue for a feature request.

License

MIT License

vue-clipboard2's People

Contributors

camdenmoors avatar ctf0 avatar daniel4digital avatar dependabot[bot] avatar gustawdaniel avatar inndy avatar jamessouth avatar robmazur avatar vlad-ro avatar zhangzheng-zz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-clipboard2's Issues

Uncaught ReferenceError: VueClipboard

Hello, this my code attempting to set up use of Vue clipboard, note this is cdn because its a completely standalone page with no back end what so ever. I know nothing about webpack or any of the other massively complex packages i've seen that actually support these "20 lines or less" examples.

  <script type="text/javascript" src="https://unpkg.com/vue"></script>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue-clipboards.min.js">
  </script>
<script>

 Vue.use(VueClipboard)

When I load the page i get this in the console

 Uncaught ReferenceError: VueClipboard is not defined
    at html:80

How do I actually reference the code you have packaged here? Why does Vue work just fine from a cdn but I cannot reference anything in the second one?

autoSetContainer opion impossible to set to true

It seems that documentation is incorrect about being able to set VueClipboard.config.autoSetContainer because in the code it is set through an independent variable and when setting container option this variable is checked instead of VueClipboard.config.autoSetContainer

var VueClipboardConfig = {
  autoSetContainer: false
};

Also VueClipboard.config evaluates to udnefined

If it existed after ajax an error will occur !

// success this.url = 'http://test.czbapp.com/paymentonline' this.$copyText(this.url).then(function (e) { console.log('成功') }, function (e) { console.log('失败') }) await Contract.order.copyH5PayLink(id)

// error await Contract.order.copyH5PayLink(id) this.url = 'http://test.czbapp.com/paymentonline' this.$copyText(this.url).then(function (e) { console.log('成功') }, function (e) { console.log('失败') })

Multiple Buttons - 1 v-clipboard

I have 2 buttons and v-clipboard is only attached to one button... however it's only working on the first button...

<div class="row">
  <div class="col-5">
    <q-btn icon="fa-refresh" color="primary" @click="Generate(10)">Generate</q-btn>
  </div>
  <div class="col-7" v-if="user.generated">
    <div class="row">
      <div class="col-5">
        <div class="text-center" style="margin-top: 5px; font-size: 20px; font-weight: bold">{{ user.test }}
        </div>
      </div>
      <div class="col-7 text-center">
        <q-btn 
	  color="secondary" 
	  icon="fa-clipboard"
	  v-clipboard:copy="user.test"
	  v-clipboard:success="copied()"
	>Copy to Clipboard</q-btn>
      </div>
    </div>
  </div>
</div>```

Whenever I click on the generated button, it is copying to the clipboard, even though it's not attached to that system at all
  

Use in Bootstrap Modals

Hi,

I'm having some issues using this directive in a Bootstrap modal window.
According to the clipboard.js documentation, we have to define the container in this case:

For use in Bootstrap Modals or with any other library that changes the focus you'll want to set the focused element as the container value.

new Clipboard('.btn', {
    container: document.getElementById('modal')
});

Is there a way to pass the container reference?

Thanks, I appreciate your help!

Cheers, Sebi

Success and error firing on startup

I've this code in my Vue

<a href="#" v-clipboard:copy="`some text`" v-clipboard:success="handleCopyStatus(true)" v-clipboard:error="handleCopyStatus(false)">Copy</a>

and under the Javascript script I've this part

methods: {
  handleCopyStatus(status) {
    console.log(status);
    this.copied = status
  }
}

I noticed the console.log was fired setting the copied to true and false successively. Then when I click on my Copy button it actually doesn't change the copied value. The copy to clipboard does work tho.

What's happening here ? Is it a bug ?

PS : I'm new to VueJS so I might have done something wrong.

IE 11

I can't seem to get this to work in IE 11. Should it? Thank you.

can't get the sample to work

Mac 10.11
chrome Version 61.0.3163.100 (Official Build) (64-bit)
Vue 2.52

I get the success window with the correct string, but the clipboard does not get the new string

console does not show anything

ios9 无法复制

ios9 无法复制
代码:
this.$copyText(text).then(function (e) { //success console.log('1') _this.copyVisible = true _this.copyTips = '复制成功' }, function (e) { //error console.log(e) })

how to preserve text format

for example if i copied a text with a char like => the copied text will become =&gt;, so is there a way to add an option to disable that ?

在火狐浏览器上不兼容,复制不成功

提示:document.execCommand('cut'/'copy') 被拒绝,因为它不是从短时运行的用户生成的事件处理程序内部进行调用。
onClick写在一个弹窗中,这个也是用户触发呢,代码如下:
onClick: function () {
_this.$copyText( cardNo ).then( e =>{
_this.$tip('您的卡号已复制');
},e =>{
_this.$tip('复制异常,请重试');
})
}

辛苦帮忙看看,谢谢

This relative module was not found:

This relative module was not found:

  • ./clipboard-action in ./node_modules/vue-clipboard2/dist/vue-clipboard.min.js
    I use webpack, first time when i use npm run dev it works. but i use npm run prod an have errors now when i use npm run dev i have this error why is that ?

Uncaught (in promise) Error: [vue-clipboards] Invalid value. Please use a valid value.

Since I use v-if in my DOM, vue clipboards will throw an error like this when the copy-text-data haven't ready. Must users use vue-clipboards when the copy-text-data is ready?

Actually, I can make fake data for the vue clipboard to copy inside mounted. But it is not a good way. Could you please handle this situation where the copy data is not ready for vue-clipboards. Thanks!

Btw, the version I am using is 1.2.4

[Vue warn]: Failed to resolve directive: clipboard

[Vue warn]: Failed to resolve directive: clipboard

I am getting this issue sometimes, but mostly not. And it causes the copying functionality to not work. It is really hard to debug, because it happens very rarely.

I do not know if this is an issue with vue-clipboard2 itself or if it is a vue thing, but I have no clue because I am pretty new to vue in general. Can I listen to this warning in javascript?

Copy HTML Text vs Plain Text

Is there any way to copy text as text/html instead of the default text/plain?

When I copy text like "This is a test", the italic tags are copied too instead of them being styled.

It appears that clipboard.js is able to do this. Is this also possible with vue-clipboard?

Thanks!

How can I use this.$copyText in async method?

I can't use this plugin in my app. Do you have any good ideas? otherwise, I have use it like this:

// app.ts
import VueClipboard from 'vue-clipboard2';
Vue.use(VueClipboard);

// component.vue
<template>
<button @click="doCopy">Copy</button>
</template>
export default Vue.extend({
 name: '',
 data: {},
 methods: {
  async doCopy(){
    this.$copyText('copy content').then(function(e){console.log(e)})
  }
 }
})

Do you have any ideas for making it work in async function?

Unable to copy large text/json file

Is there like a limit to how large this plugin can copy? When copying small text/json it works fine. But when copying large texts, it fails. Also there are no specific error message thrown.

To help you see what happened, I am trying to copy a 3000 length json file each item is an object with 4 fields email, mobileNo, firstName, lastName.

Object

{
    "email": "[email protected]",
    "mobile": "1234567",
    "firstName": "Emma",
    "lastName": "Stone"
}
... 2999 more

安卓无法重复复制问题

安卓手机复制文字之后只能粘贴一次。之后再复制就不能粘贴了。请问如何解决?苹果手机可以正常使用

how to copy on something else other than click

atm the lib support only copying on click event, but what if we want to change that to something like click.ctrl or any other event ?

in the original clipboard.js u can use data-clipboard-text and use any event to call
new Clipboard(.itemClass)

CSS - user-select: none; prevents copy?

If this code is in place on the document then you cannot use copy feature?

* {
	user-select: none;
}

Have tried to use this on selections but it did not work - I'm guessing the clipboard script is pasting the data somewhere in the DOM copying and removing?

.enableSelection {
	user-select:text;
}

core.js

WARNING: We noticed you're using the useBuiltIns option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the corejs option.
You should also be sure that the version you pass to the corejs option matches the version specified in your package.json's dependencies section. If it doesn't, you need to run one of the following commands:

关于config配置项

有一个插件的配置项很适合这个插件,比如说

  1. config's default successful message

  2. config‘s default failed message

Failed to resolve directive: clipboard

Hi,
I have an issue, I want to generate a clipboard from a v-for & feed v-clipboard success from data but I have this error & I don't know why I have this.

main.js

import Vue from "vue";
import Vuex from "vuex";
import VueResource from "vue-resource";
import VueClipboard from "vue-clipboard2";
import VueLoading from "vuex-loading";
import { sync } from "vuex-router-sync";
import App from "./App";
import router from "./router";
import store from "./store";
import * as filters from "./helpers/filters";
import * as constants from "./helpers/constants";

Vue.config.productionTip = false;

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key]);
});

Vue.use(VueResource);
Vue.use(Vuex);
Vue.use(VueLoading);
Vue.use(VueClipboard);

sync(store, router);

Vue.http.options.root = constants.rootApi;

Vue.prototype.$appName = constants.appName;

/* eslint-disable no-new */
const app = new Vue({
  el: "#app",
  router,
  store,
  components: { App },
  template: "<App/>",
  vueLoading: new VueLoading({ useVuex: true }),
  filters: filters
});

CopyToClipBoard component

<template>
  <button type="button"
      v-clipboard:copy="message"
      v-clipboard:success="onCopy">
        <slot></slot>
      </button>
</template>

<script>

import Vue from 'Vue'

export default Vue.component('copy-clipboard-button', {
  props: {
    message: String
  },
  methods: {
    onCopy: function (e) {
      e.stopPropagation();
      alert('You just copied: ' + e.text)
    }
  }
})
</script>

Sortable table get data & render a table

<template>
 <div class="table-wrapper">
   <table class="table">
    <thead>
      <tr>
        <th v-for="(obj, index) in columns" :key="index"
          @click="sortBy(obj.name)"
          :class="{ active: sortKey == obj.name, 'text-right': obj.align === 'right' }" class="pointer">
          {{ obj.label }}
          <span class="arrow" :class="sortOrders[obj.name] > 0 ? 'asc' : 'dsc'">
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(entry, index) in filteredData" :key="index" @click="onBodyRowClick(entry)" class="pointer">
        <td v-for="(obj, index) in columns" :key="index"
          :class="{ 'text-right': obj.align === 'right' }">
          <img :src="getImageSrc(entry.item_id)" alt="" v-if="obj.name === 'name'" width="48">

          {{obj.filters ? dynamicFilters(entry[obj.name], obj.filters) : entry[obj.name]}}

          <copy-clipboard-button :message="getShopLocationCommand(entry.map, entry.x, entry.y)" v-if="obj.name === 'map'">Copy command</copy-clipboard-button>
        </td>
      </tr>
    </tbody>
  </table>
   <div v-if="filteredData.length === 0">
        <p>Aucun résultat</p>
    </div>
 </div>
</template>

<script>
import Vue from 'Vue'
import helpers from '@/helpers/helpers'
import CopyClipboardButton from '@/components/ui/CopyClipboardButton.vue'

export default Vue.component('sortable-table', {
  props: {
    datas: { default: () => [], type: [Array, Object, String] },
    columns: Array,
    filterKey: String
  },
  components: {
    CopyClipboardButton
  },
  data () {
    let sortOrders = {}

    this.columns.forEach(function (key) {
      sortOrders[key] = 1
    })

    return {
      sortKey: '',
      sortOrders: sortOrders
    }
  },
  computed: {
    filteredData () {
      let sortKey = this.sortKey
      let filterKey = this.filterKey && this.filterKey.toLowerCase()
      let order = this.sortOrders[sortKey] || 1
      let datas = this.datas

      if (filterKey) {
        datas = datas.filter(function (row) {
          return Object.keys(row).some(function (key) {
            return String(row[key]).toLowerCase().indexOf(filterKey) > -1
          })
        })
      }

      if (sortKey) {
        datas = datas.slice().sort(function (a, b) {
          a = a[sortKey]
          b = b[sortKey]
          return (a === b ? 0 : a > b ? 1 : -1) * order
        })
      }

      return datas
    }
  },
  methods: {
    onBodyRowClick(data) {
      this.$emit('onRowClick', data.id);
    },
    getImageSrc(itemId) {
      if (!itemId) return

      return helpers.getImageItem(itemId);
    },
    getShopLocationCommand(map, x, y) {
      return `/nav ${map} ${x}/${y}`
    },
    sortBy(key) {
      this.sortKey = key
      this.sortOrders[key] = this.sortOrders[key] * -1
    },
    dynamicFilters(value, filters) {
      let filteredVal = filters.map((filter) => {
        if (this.$root.$options.filters[filter] instanceof Function) {
          return this.$root.$options.filters[filter](value)
        } else {
          return value
        }
      })

      return filteredVal.toString();
    }
  }
})

</script>

Have you an idea where the problem is ?

Thanks

How to copy inside a async

I sent a ajax and got data in callback ,then I wanted to copy the data into my clipboard but failed.So,what should I do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.