效果如下
第一步 安装highlight.js
yarn add highlight.js
第二步 在main.js中引入
import hl from 'highlight.js' // 导入代码高亮文件
import 'highlight.js/styles/a11y-dark.css' // 导入代码高亮样式
// 自定义一个代码高亮指令
Vue.directive('highlight', function (el) {
const blocks = el.querySelectorAll('pre code')
blocks.forEach((block) => {
hl.highlightBlock(block)
})
})
第三步 创建组件
<template>
<div class="copy-code-container">
<div class="copy-container flex-row">
<a-tooltip>
<template slot="title"> 复制代码 </template>
<div class="ant-btn" @click="handleCopy(code, $event)"> <a-icon type="copy"></a-icon></div>
</a-tooltip>
<a-tooltip>
<template slot="title"> 显示代码 </template>
<a-icon @click="handeShowCode" type="code" />
</a-tooltip>
</div>
<div class="code-palce-container" :class="{ 'show-code': showCode }">
<div class="code-box" v-highlight>
<pre>
<code class="javascirpt">{{code}}</code>
</pre>
</div>
</div>
</div>
</template>
<script>
import clip from '@/utils/clipboard' // use clipboard directly
export default {
data () {
return {
showCode: false
}
},
props: {
code: {
type: String,
default: ''
}
},
methods: {
handeShowCode () {
this.showCode = !this.showCode
},
handleCopy (text, event) {
clip(text, event)
}
}
}
</script>
<style lang="less" scoped>
.copy-code-container {
width: 100%;
.copy-container {
width: 100%;
height: 50px;
justify-content: center;
align-items: center;
position: relative;
.ant-btn{
width: 58px;
height: 38px;
margin: 0;
border: none;
box-shadow: none;
background-color: transparent;
padding: 0;
}
i {
cursor: pointer;
font-size: 18px;
padding: 10px 20px;
}
}
.code-palce-container {
width: 100%;
height: 0;
overflow: hidden;
transition: all linear 0.1s;
&.show-code {
height: 100%;
}
.code-box {
::v-deep .hljs {
padding: 0 20px;
line-height: 25px;
}
}
}
}
</style>
效果如图:点击显示代码
第四步: 使用组件
<copy-code :code="code"> </copy-code>
export default {
data () {
return {
code: `<template>
<div>
<a-button type="primary">
Primary
</a-button>
<a-button>Default</a-button>
<a-button type="dashed">
Dashed
</a-button>
<a-button type="danger">
Danger
</a-button>
<a-config-provider :auto-insert-space-in-button="false">
<a-button type="primary">
按钮
</a-button>
</a-config-provider>
<a-button type="primary">
按钮
</a-button>
<a-button type="link">
Link
</a-button>
</div>
</template>`
}
}
}
第五步 实现点击复制代码clipboard.js。clipboard.js copy地址
import Vue from 'vue'
import Clipboard from 'clipboard'
function clipboardSuccess () {
Vue.prototype.$message.success({
content: '复制成功',
duration: 1.5
})
}
function clipboardError () {
Vue.prototype.$message.error({
content: '复制失败',
duration: 1.5
})
}
export default function handleClipboard (text, event) {
const clipboard = new Clipboard(event.target, {
text: () => text
})
clipboard.on('success', () => {
clipboardSuccess()
clipboard.destroy()
})
clipboard.on('error', () => {
clipboardError()
clipboard.destroy()
})
clipboard.onClick(event)
}