一、common/function.js 方法封装
svgToUrl(url) {
var encoded = url
.replace(//g, "")
.replace(/[\r\n]/g, " ")
.replace(/"/g, `'`)
.replace(/%/g, "%25")
.replace(/&/g, "%26")
.replace(/#/g, "%23")
.replace(/{/g, "%7B")
.replace(/}/g, "%7D")
.replace(/</g, "%3C")
.replace(/>/g, "%3E");
let res = '"' + `data:image/svg+xml,${encoded}` + '"';
return res;
},
svgChangeColor(url, color, type, index) {
let modifiedStr;
if (type == 'two-tone') {
let color2 = color;
let newColor = color2.replace("#", "%23");
let str = url;
let pattern = /%23[a-zA-Z0-9]{6}/g;
let matches = str.match(pattern);
if (matches && matches.length > 0) {
modifiedStr = str.replace(matches[index], newColor);
}
return modifiedStr;
} else {
modifiedStr = url.replace(/%23[a-zA-Z0-9]{6}/g, color.replace("#",
"%23"));
return modifiedStr;
}
},
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
二、utils 下新建 svg.js 用来存放svg图
const svgObj = {
ztSvg: ''
}
export default svgObj
三、 页面使用
<template>
<view class="title-box">
<view :style="{'background-image': 'url('+ztSvg+')'}" class="icon"></view>
<view>{{$t('task.homework')}}</view>
</view>
</template>
<script>
import svgObj from '@/utils/svg.js'
export default {
data() {
return {
ztSvg: svgObj.ztSvg,
}
},
onLoad() {
this.ztSvg= svgObj.ztSvg
this.ztSvg = this.$f.svgChangeColor(this.$f.svgToUrl(this.ztSvg), '#333333')
},
}
</script>
<style scoped lang="scss">
.title-box {
font-size: 28rpx;
font-family: PingFangSC, PingFang SC;
font-weight: 600;
color: #333333;
display: flex;
align-items: center;
image {
width: 32rpx;
height: 28rpx;
margin-right: 16rpx;
}
}
.icon {
background-size: 100% 100%;
background-repeat: no-repeat;
height: 50rpx;
width: 40rpx;
margin-right: 6rpx;
}
</style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43