Front-end implementation of copy function

First case:

Click the copy button to copy text or other content. Below I use the copied content as a parameter to perform the operation.

<button @click="copy('This is a piece of content')" >Copy</button>

//Copy method

copy (value) {

        ​​​​//Create input tags

        var input = document.createElement('input')

        //Set the value of input to the content that needs to be copied

        input.value = value;

        ​​​​//Add input tag

        document.body.appendChild(input)

        ​​​​//Select the input tag

        input.select()

        ​​​​//Execute copy

        document.execCommand('copy')

        //Success message

        This.$message.success('Copy successfully!')

        ​​​​//Remove the input tag

        document.body.removeChild(input)

},

Second case:

Click the copy button to copy the contents of the input box

<template>
        <div id="app">
                请输入你需要复制的内容:<input id="copy" v-model="message"/>
                <button v-on:click="copy()">复制</button>
        </div>
</template>

<script>
export default {
        name: 'App',
        data() {
                return {
                        message: ''
                }

        },
        methods: {
                copy () {
                        //获取input对象
                        var input = document.getElementById('copy')
                        //选中input标签
                        input.select()
                        //执行复制
                        document.execCommand('copy')
                        this.$message.success('复制成功!')
                },
        },
}
</script>

Guess you like

Origin blog.csdn.net/weixin_50999303/article/details/130942617