Home  >  Article  >  Web Front-end  >  [VuePress in action] Take you step by step to develop a code copy plug-in

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

青灯夜游
青灯夜游forward
2022-01-21 19:23:114464browse

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:juejin.cn. If there is any infringement, please contact admin@php.cn delete