search
HomeWeb Front-endVue.js[VuePress in action] Take you step by step to develop a code copy plug-in

This article will take you to understand the actual combat of VuePress and introduce how to develop a VuePress plug-in (code copy plug-in) from scratch. I hope it will be helpful to everyone!

[VuePress in action] Take you step by step to develop a code copy plug-in

In the process of building a VuePress blog, not all plug-ins can meet the needs, so in this article we take the implementation of a code copy plug-in as an example to teach you how to Implement a VuePress plug-in from scratch.

Local development

The first problem to be solved when developing a plug-in is how to develop it locally. We checked the "Developing plug-in" chapter of the VuePress 1.0 official document and did not find it. Solution, but in the "Local Plug-in" of the VuePress 2.0 official document, it is written:

It is recommended that you use the configuration file directly as a plug-in, because almost all Plug-in APIs can be used in configuration files, which is more convenient in most scenarios.

But if you have too many things to do in the configuration file, it is better to extract them into separate plugins and use them by setting absolute paths or via require :

module.exports = {
  plugins: [
    path.resolve(__dirname, './path/to/your-plugin.js'),
    require('./another-plugin'),
  ],
}

Then let’s get started!

Initialize the project

We create a new folder vuepress-plugin-code-copy under the .vuepress folder to store the plug-in Relevant code, and then enter the folder with the command line, execute npm init, and create package.json. At this time, the directory of the file is:

.vuepress
├─ vuepress-plugin-code-copy 
│  └─ package.json
└─ config.js

We are in Create a new index.js file under vuepress-plugin-code-copy, refer to the writing method in Official Document Plug-in Example, we use the function form of the returned object, This function accepts the plug-in configuration options as the first parameter, and the ctx object containing the compile-time context as the second parameter:

module.exports = (options, ctx) => {
   return {
      // ...
   }
}

Refer to the name in the official document Option API, and For the ready hook in the life cycle function, we write an initial test code:

module.exports = (options, ctx) => {
    return {
        name: 'vuepress-plugin-code-copy',
        async ready() {
            console.log('Hello World!');
        }
    }
 }

At this time we run yarn run docs:dev, which can be used during the running process See our plug-in name and print results in:

[VuePress in action] Take you step by step to develop a code copy plug-in

Plug-in design

Now we can imagine the effect of our code copying the plug-in, I think The effect to be achieved is:

There is a Copy text button in the lower right corner of the code block. After clicking, the text changes to Copied! Then the text changes to Copy again after one second, and the code in the code block is copied to the clipboard when clicked. The expected performance effect is as follows:

[VuePress in action] Take you step by step to develop a code copy plug-in

plugin Development

If it is in a Vue component, we can easily achieve this effect. When the root component is mounted or updated, use document.querySelectorGet all code blocks, insert a button element, and then bind a click event to the button element. When the click event is triggered, copy the code to the clipboard, then modify the text, and then modify the text after 1 second.

Does the VuePress plug-in have a way to control the life cycle of the root component? We check the Option API of the VuePress official documentation and find that VuePress provides a clientRootMixin method:

points to the path to the mixin file, which allows you to control the life cycle of the root component.

Look at the sample code:

// 插件的入口
const path = require('path')

module.exports = {
  clientRootMixin: path.resolve(__dirname, 'mixin.js')
}
// mixin.js
export default {
  created () {},
  mounted () {}
}

Isn’t this what we need? Then let’s do it, modify the content of index.js to:

const path = require('path');

module.exports = (options, ctx) => {
    return {
        name: 'vuepress-plugin-code-copy',
        clientRootMixin: path.resolve(__dirname, 'clientRootMixin.js')
    }
 }

Create a new clientRootMixin.js# under vuepress-plugin-code-copy ##File, code writing:

export default {
    updated() {
        setTimeout(() => {
            document.querySelectorAll('div[class*="language-"] pre').forEach(el => {
								console.log('one code block')
            })
        }, 100)
    }
}

Refresh the page in the browser, and then view the print:

[VuePress in action] Take you step by step to develop a code copy plug-in

接下来就要思考如何写入按钮元素了。

当然我们可以使用原生 JavaScript 一点点的创建元素,然后插入其中,但我们其实是在一个支持 Vue 语法的项目里,其实我们完全可以创建一个 Vue 组件,然后将组件的实例挂载到元素上。那用什么方法挂载呢?

我们可以在 Vue 的全局 API 里,找到 Vue.extendAPI,看一下使用示例:

// 要挂载的元素
<div id="mount-point"></div>
// 创建构造器
var Profile = Vue.extend({
  template: &#39;<p>{{firstName}} {{lastName}} aka {{alias}}</p>&#39;,
  data: function () {
    return {
      firstName: &#39;Walter&#39;,
      lastName: &#39;White&#39;,
      alias: &#39;Heisenberg&#39;
    }
  }
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount(&#39;#mount-point&#39;)

结果如下:

// 结果为:
<p>Walter White aka Heisenberg</p>

那接下来,我们就创建一个 Vue 组件,然后通过 Vue.extend 方法,挂载到每个代码块元素中。

vuepress-plugin-code-copy下新建一个 CodeCopy.vue 文件,写入代码如下:

<template>
    <span class="code-copy-btn" @click="copyToClipboard">{{ buttonText }}</span>
</template>

<script>
export default {
    data() {
        return {
            buttonText: &#39;Copy&#39;
        }
    },
    methods: {
        copyToClipboard(el) {
            this.setClipboard(this.code, this.setText);
        },
        setClipboard(code, cb) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(code).then(
                    cb,
                    () => {}
                )
            } else {
                let copyelement = document.createElement(&#39;textarea&#39;)
                document.body.appendChild(copyelement)
                copyelement.value = code
                copyelement.select()
                document.execCommand(&#39;Copy&#39;)
                copyelement.remove()
                cb()
            }
        },
        setText() {
            this.buttonText = &#39;Copied!&#39;

            setTimeout(() => {
                this.buttonText = &#39;Copy&#39;
            }, 1000)
        }
    }
}
</script>

<style scoped>
.code-copy-btn {
    position: absolute;
    bottom: 10px;
    right: 7.5px;
    opacity: 0.75;
    cursor: pointer;
    font-size: 14px;
}

.code-copy-btn:hover {
    opacity: 1;
}
</style>

该组件实现了按钮的样式和点击时将代码写入剪切版的效果,整体代码比较简单,就不多叙述了。

我们修改一下 clientRootMixin.js

import CodeCopy from &#39;./CodeCopy.vue&#39;
import Vue from &#39;vue&#39;

export default {
    updated() {
        // 防止阻塞
        setTimeout(() => {
            document.querySelectorAll(&#39;div[class*="language-"] pre&#39;).forEach(el => {
              	// 防止重复写入
                if (el.classList.contains(&#39;code-copy-added&#39;)) return
                let ComponentClass = Vue.extend(CodeCopy)
                let instance = new ComponentClass()
                instance.code = el.innerText
                instance.$mount()
                el.classList.add(&#39;code-copy-added&#39;)
                el.appendChild(instance.$el)
            })
        }, 100)
    }
}

这里注意两点,第一是我们通过 el.innerText 获取要复制的代码内容,然后写入到实例的 code 属性,在组件中,我们是通过 this.code获取的。

第二是我们没有使用 $mount(element),直接传入一个要挂载的节点元素,这是因为 $mount() 的挂载会清空目标元素,但是这里我们需要添加到元素中,所以我们在执行 instance.$mount()后,通过 instance.$el获取了实例元素,然后再将其 appendChild 到每个代码块中。关于 $el的使用可以参考官方文档的 el 章节

此时,我们的文件目录如下:

.vuepress
├─ vuepress-plugin-code-copy 
│  ├─ CodeCopy.vue
│  ├─ clientRootMixin.js
│  ├─ index.js
│  └─ package.json
└─ config.js

至此,其实我们就已经实现了代码复制的功能。

插件选项

有的时候,为了增加插件的可拓展性,会允许配置可选项,就比如我们不希望按钮的文字是 Copy,而是中文的「复制」,复制完后,文字变为 「已复制!」,该如何实现呢?

前面讲到,我们的 index.js导出的函数,第一个参数就是 options 参数:

const path = require(&#39;path&#39;);

module.exports = (options, ctx) => {
    return {
        name: &#39;vuepress-plugin-code-copy&#39;,
        clientRootMixin: path.resolve(__dirname, &#39;clientRootMixin.js&#39;)
    }
 }

我们在 config.js先写入需要用到的选项:

module.exports = {
    plugins: [
      [
        require(&#39;./vuepress-plugin-code-copy&#39;),
        {
          &#39;copybuttonText&#39;: &#39;复制&#39;,
          &#39;copiedButtonText&#39;: &#39;已复制!&#39;
        }
      ]
    ]
}

我们 index.js中通过 options参数可以接收到我们在 config.js 写入的选项,但我们怎么把这些参数传入 CodeCopy.vue 文件呢?

我们再翻下 VuePress 提供的 Option API,可以发现有一个 define API,其实这个 define 属性就是定义我们插件内部使用的全局变量。我们修改下 index.js

const path = require(&#39;path&#39;);

module.exports = (options, ctx) => {
    return {
        name: &#39;vuepress-plugin-code-copy&#39;,
        define: {
            copybuttonText: options.copybuttonText || &#39;copy&#39;,
            copiedButtonText: options.copiedButtonText || "copied!"
        },
        clientRootMixin: path.resolve(__dirname, &#39;clientRootMixin.js&#39;)
    }
 }

现在我们已经写入了两个全局变量,组件里怎么使用呢?答案是直接使用!

我们修改下 CodeCopy.vue 的代码:

// ...
<script>
export default {
    data() {
        return {
            buttonText: copybuttonText
        }
    },
    methods: {
        copyToClipboard(el) {
            this.setClipboard(this.code, this.setText);
        },
        setClipboard(code, cb) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(code).then(
                    cb,
                    () => {}
                )
            } else {
                let copyelement = document.createElement(&#39;textarea&#39;)
                document.body.appendChild(copyelement)
                copyelement.value = code
                copyelement.select()
                document.execCommand(&#39;Copy&#39;)
                copyelement.remove()
                cb()
            }
        },
        setText() {
            this.buttonText = copiedButtonText

            setTimeout(() => {
                this.buttonText = copybuttonText
            }, 1000)
        }
    }
}
</script>
// ...

最终的效果如下:

[VuePress in action] Take you step by step to develop a code copy plug-in

代码参考

完整的代码查看:https://github.com/mqyqingfeng/Blog/tree/master/demos/VuePress/vuepress-plugin-code-copy

【相关推荐:vue.js视频教程

The above is the detailed content of [VuePress in action] Take you step by step to develop a code copy plug-in. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!