項目場景:
《數據可視化之模塊邊框繪製,以及組件開發》介紹了css3中關於borderImage的相關配置,並且實現了一個border圖片渲染的插件。其原理也是相當簡單,這裏就不過多贅述了,今天要做的是實現Vue3的組件(圖片邊框渲染通用組件)。
解決方案:
1、準備
- 一張邊框圖片
- nodejs
- vue-cli
2、快速開始
- 創建項目
vue create dev-datav-border-view
- 添加組件
<template>
<div class="twoke-view-container">
<div class="twoke-view-border" :id="id"></div>
<slot></slot>
</div>
</template>
<script>
import {
ref, onMounted } from 'vue'
import uuidv4 from 'uuid'
export default {
name: 'TwokeBorderView',
props: {
options: {
type: Object,
default: () => {
return {
}
}
}
},
setup (props) {
const {
slice,source,padding,custom} = props.options
const id = ref(`border-view-${
uuidv4()}`)
const onLoadBorder = () => {
const border = document.getElementById(id.value)
border.style.borderImageSource = `url(${
source})`
border.style.borderImageSlice = ` ${
slice[0]} ${
slice[1]} ${
slice[2]} ${
slice[3]}`
border.style.borderImageWidth = `${
slice[0]}px ${
slice[1]}px ${
slice[2]}px ${
slice[3]}px`
border.style.borderWidth = `${
slice[0]}px ${
slice[1]}px ${
slice[2]}px ${
slice[3]}px`
const content = border.nextElementSibling
content.style.position = "absolute"
content.style.top = "50%"
content.style.left = "50%"
content.style.transform= "translate(-50%,-50%)"
if (padding&&!custom) {
let width = undefined
let height = undefined
if (padding.length===1) {
width = content.parentElement.clientWidth - padding[0]*2
height = content.parentElement.clientHeight - padding[0]*2
}else if(padding.length==2) {
width = content.parentElement.clientWidth - padding[0]*2
height = content.parentElement.clientHeight - padding[1]*2
}
content.style.width = `${
width}px`
content.style.height = `${
height}px`
}
}
onMounted(() => {
onLoadBorder()
})
return {
id
}
}
}
</script>
<style lang="scss" scoped>
.twoke-view-container {
position: relative;
width: 100%;
height: 100%;
.twoke-view-border {
border: 1px solid transparent;
width: 100%;
height: 100%;
box-sizing: border-box;
}
}
</style>
3、快速使用(這裏是用的全局安裝組件)
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<twoke-border-view style="width:400px;height:300px" :options="{padding:[10],slice: [9, 40, 9, 40], source: require('../assets/border.png')}">
<div class="text">模塊</div>
</twoke-border-view>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
}
}
</script>
<style lang="scss" scoped>
.text {
color: blue;
}
</style>
組件庫
碼雲組件庫,我把寫的一些組件放在這個下面,有興趣的話可以看看。
安裝
npm i twoke-datav-vue -S
克隆源碼
git clone https://gitee.com/twoke/twoke-datav-vue3.git