User-defined instructions to realize one-key copy function

This method uses a global custom command, and takes out a separate file to import the registered


Here we need to master the Vue.use() method

We can pass an object or a function as a parameter,

If it is an object, the install method must be provided. If it is a function, this function will be called as the install method

The install method receives a Vue instance as a parameter, through which we can register a series of global instructions, components, filters, etc.

Custom directive js file content:

export default {
  install (Vue) {
    Vue.directive('copy', {
      bind (el, bindginds) {
        el.$value = bindginds.value
        el.handle = () => {
          navigator.clipboard.writeText(el.$value)
        }
        el.addEventListener('click', el.handle)
      },
        update(el, bindginds){
            el.$value = bindings.value
         }

    })
  }
}

main.js file

import directives from './directives/index'
Vue.use(directives)

index file

    <button v-copy="uname">一键复制 </button>
//uname:是data中的数据

Guess you like

Origin blog.csdn.net/shmilynn_/article/details/128882219