In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you how to use VuePress to develop a code replication plug-in related knowledge, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you can learn something after reading this article, let's take a look at it.
Local development
But if you have too much to do in the configuration file, it's best to extract them into separate plug-ins and use them by setting absolute paths or through 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 vuepress-plugin-code-copy folder under the .vuepress folder to store plug-in-related code, then go to this folder on the command line, execute npm init, and create package.json. The directory of the files is:
.vuepress ├─ vuepress-plugin-code-copy │ └─ package.json └─ config.js
Let's create a new index.js file under vuepress-plugin-code-copy. Referring to the official documentation plug-in example, we use the function form of the return object, which accepts the plug-in's configuration option as the first parameter and the ctx object containing the compile-time context as the second parameter:
Module.exports = (options, ctx) = > {return {/ /...}}
Referring to the name in the official document Option API and the ready hook in the lifecycle function, we write an initial test code:
Module.exports = (options, ctx) = > {return {name: 'vuepress-plugin-code-copy', async ready () {console.log (' Hello Worldwide');}
At this point, we run yarn run docs:dev, and we can see our plug-in name and print result during the run:
Plug-in design
Now we can imagine the effect of our code replication plug-in, and what I want to achieve is:
There is a Copy text button in the lower right corner of the code block, and the text becomes Copied! Then a second later the text is changed back to Copy, and the code in the code block is copied to the clipboard when clicked.
Plug-in development
If it is in the Vue component, we can easily achieve this effect, in the root component mounted or updated, use document.querySelector to get all the code blocks, insert a button element, and then bind the click event on the button element. When the click event is triggered, the code is copied to the clipboard, and then modify the text, and then modify the text 1s later.
Is there a way for the VuePress plug-in to control the life cycle of the root component? When we look at the Option API of the official VuePress documentation, we can see that VuePress provides a clientRootMixin method:
The path to the mixin file, which allows you to control the life cycle of the root component
Take a look at the sample code:
/ / entry of the plug-in const path = require ('path') module.exports = {clientRootMixin: path.resolve (_ _ dirname,' mixin.js')} / / mixin.jsexport default {created () {}, mounted () {}}
Isn't that what we need? Let's go ahead and modify the content of index.js as follows:
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 file under vuepress-plugin-code-copy and write the code as follows:
Export default {updated () {setTimeout (() = > {document.querySelectorAll ('div [class * = "language-"] pre') .forEach (el = > {console.log (' class)})}, 100)}}
Refresh the page in the browser, and then check the print:
The next step is to think about how to write button elements.
Of course, we can use native JavaScript to create elements and insert them, but we are actually in a project that supports Vue syntax, we can actually create a Vue component, and then mount an instance of the component to the element. Then how to mount it?
We can find Vue.extendAPI in the global API of Vue and take a look at the usage example:
/ / elements to be mounted / / create constructor var Profile = Vue.extend ({template:'
{{firstName}} {{lastName}} aka {{alias}}
', data: function () {return {firstName:' Walter', lastName: 'White', alias:' Heisenberg'}) / / create an instance of Profile and mount it to an element. New Profile (). $mount ('# mount-point')
The results are as follows:
/ / the result is:
Walter White aka Heisenberg
Next, we create a Vue component and then mount it into each code block element through the Vue.extend method.
Create a new CodeCopy.vue file under vuepress-plugin-code-copy and write the following code:
{{buttonText}} 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 = 'copyrighted' SetTimeout (() = > {this.buttonText = 'Copy'}, 1000)}} .code-copy-btn {position: absolute; bottom: 10px; right: 7.5px; opacity: 0.75; cursor: pointer; font-size: 14px;} .code-copy-btn:hover {opacity: 1;}
This component implements the style of the button and the effect of writing the code to the cut version when clicked, so the overall code is relatively simple and will not be described.
Let's modify the clientRootMixin.js:
Import CodeCopy from'. / CodeCopy.vue'import Vue from 'vue'export default {updated () {/ / prevent blocking setTimeout (() = > {document.querySelectorAll (' div [class * = "language-"] pre') .forEach (el = > {/ / prevent repeated writes to 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)}}
There are two things to note here. The first is that we get the content of the code to be copied through el.innerText, and then write it to the code property of the instance. In the component, we get it through this.code.
The second is that instead of using $mount (element), we pass in a node element to be mounted directly, because the mount of $mount () clears the target element, but here we need to add it to the element, so after executing instance.$mount (), we get the instance element through instance.$el, and then appendChild it into each code block. You can refer to the el section of the official documentation for the use of $el.
At this point, our file directory is as follows:
.vuepress ├─ vuepress-plugin-code-copy │ ├─ CodeCopy.vue │ ├─ clientRootMixin.js │ ├─ index.js │ └─ package.json └─ config.js
At this point, in fact, we have implemented the function of code replication.
Plug-in option
Sometimes, in order to increase the extensibility of the plug-in, the configuration will be allowed to be optional, for example, we do not want the button text to be Copy, but the Chinese "copy". After copying, the text becomes "copied"! "how can it be realized?
As mentioned earlier, the first argument to the function exported by our index.js is the options parameter:
Const path = require ('path'); module.exports = (options, ctx) = > {return {name:' vuepress-plugin-code-copy', clientRootMixin: path.resolve (_ _ dirname, 'clientRootMixin.js')}}
Let's write the options we need to use first in config.js:
Module.exports = {plugins: [require ('. / vuepress-plugin-code-copy'), {'copybuttonText':' copy', 'copiedButtonText':' replicated!' }]]}
We can receive the options we wrote in config.js through the options parameter in our index.js, but how do we pass these parameters into the CodeCopy.vue file?
When we look at the Option API provided by VuePress, we can see that there is a define API. In fact, this define attribute defines the global variables used within our plug-in. Let's modify the 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')}}
Now that we have written two global variables, how can we use them in the component? The answer is to use it directly!
Let's modify the code of CodeCopy.vue:
/ /... 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)}} / /. These are all the contents of the article "how to develop a code replication plug-in with VuePress". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.