站長資訊網
        最全最豐富的資訊網站

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        本篇文章帶大家了解一下VuePress實戰,介紹一下如果從零開發一個 VuePress 插件(代碼復制插件),希望對大家有所幫助!

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        在搭建 VuePress 博客的過程中,也并不是所有的插件都能滿足需求,所以本篇我們以實現一個代碼復制插件為例,教大家如何從零實現一個 VuePress 插件。

        本地開發

        開發插件第一個要解決的問題就是如何本地開發,我們查看 VuePress 1.0 官方文檔的「開發插件」章節,并沒有找到解決方案,但在 VuePress 2.0 官方文檔的「本地插件」里,卻有寫道:

        推薦你直接將 配置文件 作為插件使用,因為幾乎所有的插件 API 都可以在配置文件中使用,這在絕大多數場景下都更為方便。

        但是如果你在配置文件中要做的事情太多了,最好還是將它們提取到單獨的插件中,然后通過設置絕對路徑或者通過 require 來使用它們:

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

        那就讓我們開始吧!

        初始化項目

        我們在 .vuepress 文件夾下新建一個 vuepress-plugin-code-copy 的文件夾,用于存放插件相關的代碼,然后命令行進入到該文件夾,執行 npm init,創建 package.json,此時文件的目錄為:

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

        我們在 vuepress-plugin-code-copy下新建一個 index.js 文件,參照官方文檔插件示例中的寫法,我們使用返回對象的函數形式,這個函數接受插件的配置選項作為第一個參數、包含編譯期上下文的 ctx 對象作為第二個參數:

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

        再參照官方文檔 Option API 中的 name,以及生命周期函數中的 ready 鉤子,我們寫一個初始的測試代碼:

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

        此時我們運行下 yarn run docs:dev,可以在運行過程中看到我們的插件名字和打印結果:

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        插件設計

        現在我們可以設想下我們的代碼復制插件的效果了,我想要實現的效果是:

        在代碼塊的右下角有一個 Copy 文字按鈕,點擊后文字變為 Copied!然后一秒后文字重新變為 Copy,而代碼塊里的代碼則在點擊的時候復制到剪切板中,期望的表現效果如下:

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        插件開發

        如果是在 Vue 組件中,我們很容易實現這個效果,在根組件 mounted 或者 updated的時候,使用 document.querySelector獲取所有的代碼塊,插入一個按鈕元素,再在按鈕元素上綁定點擊事件,當觸發點擊事件的時候,代碼復制到剪切板,然后修改文字,1s 后再修改下文字。

        那 VuePress 插件有方法可以控制根組件的生命周期嗎?我們查閱下 VuePress 官方文檔的 Option API,可以發現 VuePress 提供了一個 clientRootMixin 方法:

        指向 mixin 文件的路徑,它讓你可以控制根組件的生命周期

        看下示例代碼:

        // 插件的入口 const path = require('path')  module.exports = {   clientRootMixin: path.resolve(__dirname, 'mixin.js') }
        // mixin.js export default {   created () {},   mounted () {} }

        這不就是我們需要的嗎?那我們動手吧,修改 index.js的內容為:

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

        vuepress-plugin-code-copy下新建一個 clientRootMixin.js文件,代碼寫入:

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

        刷新下瀏覽器里的頁面,然后查看打印:

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        接下來就要思考如何寫入按鈕元素了。

        當然我們可以使用原生 JavaScript 一點點的創建元素,然后插入其中,但我們其實是在一個支持 Vue 語法的項目里,其實我們完全可以創建一個 Vue 組件,然后將組件的實例掛載到元素上。那用什么方法掛載呢?

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

        // 要掛載的元素 <div id="mount-point"></div>
        // 創建構造器 var Profile = Vue.extend({   template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',   data: function () {     return {       firstName: 'Walter',       lastName: 'White',       alias: 'Heisenberg'     }   } }) // 創建 Profile 實例,并掛載到一個元素上。 new Profile().$mount('#mount-point')

        結果如下:

        // 結果為: <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: 'Copy'         }     },     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('textarea')                 document.body.appendChild(copyelement)                 copyelement.value = code                 copyelement.select()                 document.execCommand('Copy')                 copyelement.remove()                 cb()             }         },         setText() {             this.buttonText = 'Copied!'              setTimeout(() => {                 this.buttonText = 'Copy'             }, 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 './CodeCopy.vue' import Vue from 'vue'  export default {     updated() {         // 防止阻塞         setTimeout(() => {             document.querySelectorAll('div[class*="language-"] pre').forEach(el => {               	// 防止重復寫入                 if (el.classList.contains('code-copy-added')) return                 let ComponentClass = Vue.extend(CodeCopy)                 let instance = new ComponentClass()                 instance.code = el.innerText                 instance.$mount()                 el.classList.add('code-copy-added')                 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('path');  module.exports = (options, ctx) => {     return {         name: 'vuepress-plugin-code-copy',         clientRootMixin: path.resolve(__dirname, 'clientRootMixin.js')     }  }

        我們在 config.js先寫入需要用到的選項:

        module.exports = {     plugins: [       [         require('./vuepress-plugin-code-copy'),         {           'copybuttonText': '復制',           'copiedButtonText': '已復制!'         }       ]     ] }

        我們 index.js中通過 options參數可以接收到我們在 config.js 寫入的選項,但我們怎么把這些參數傳入 CodeCopy.vue 文件呢?

        我們再翻下 VuePress 提供的 Option API,可以發現有一個 define API,其實這個 define 屬性就是定義我們插件內部使用的全局變量。我們修改下 index.js

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

        現在我們已經寫入了兩個全局變量,組件里怎么使用呢?答案是直接使用!

        我們修改下 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('textarea')                 document.body.appendChild(copyelement)                 copyelement.value = code                 copyelement.select()                 document.execCommand('Copy')                 copyelement.remove()                 cb()             }         },         setText() {             this.buttonText = copiedButtonText              setTimeout(() => {                 this.buttonText = copybuttonText             }, 1000)         }     } } </script> // ...

        最終的效果如下:

        【VuePress實戰】手把手帶你開發一個代碼復制插件

        代碼參考

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

        贊(0)
        分享到: 更多 (0)
        網站地圖   滬ICP備18035694號-2    滬公網安備31011702889846號
        主站蜘蛛池模板: 精品蜜臀久久久久99网站| 国产福利精品在线观看| 国产成人精品曰本亚洲79ren| 亚洲国产精品国自产拍AV| 国产精品一区在线观看你懂的| 99久久久精品免费观看国产| 合区精品中文字幕| 国产免费久久精品丫丫| 免费欧美精品a在线| 精品人无码一区二区三区| 伊人 久久 精品 | 无码精品国产VA在线观看DVD| 国产麻豆精品入口在线观看| 欧美精品一区二区三区视频| 国产成人精品免费视频大全麻豆 | 亚洲Av永久无码精品三区在线| 久久久久无码精品| 久草热久草热线频97精品| 国产欧美日本亚洲精品一5| 国产精品美女久久久久AV福利| 66精品综合久久久久久久| 国产精品成人在线| 国产亚洲美女精品久久久久狼| 91精品国产高清91久久久久久| 国产精品扒开腿做爽爽爽视频| 精品人妻系列无码天堂| 国产精品无套内射迪丽热巴| 国产精品9999久久久久| 国产精品视频永久免费播放| 久久99精品久久久久久动态图| 久久精品水蜜桃av综合天堂| 久久久久亚洲精品天堂| 久久久久99精品成人片直播| 精品国产乱码一区二区三区| 国产精品毛片VA一区二区三区| 99久久成人国产精品免费| 精品久久久久久久久中文字幕| 一区二区精品在线| 国产呦小j女精品视频| 手机日韩精品视频在线看网站| 在线观看自拍少妇精品|