Vue?+?element-ui?背景圖片設置方式
element-ui 背景圖片設置
初學vue 看到其他網(wǎng)址都有些背景圖片,于是試著自己也寫了一下,表述不好請見諒
實現(xiàn)效果


以下是如何實現(xiàn):
找到你想要設置背景圖片的頁面

data里設置url
data() {
return {
url: '',
urlList: [],
timer: null
}
},
設置背景圖片綁定url,并填滿頁面
<div class="pull-height animated" :class="{'zoomOutUp': isLock}" :style="{backgroundImage:'url('+url+')'}" style="background-size: 100% 100%">
</div>
將子組件用div包裹,設置子組件透明度
<div class="index"> </div>
.index {
filter:alpha(Opacity=85);
-moz-opacity:0.85;
opacity: 0.85;
}
這樣背景圖片就設置好了,只要將url替換成圖片連接即可
接下來用element-ui的upload組件來設置url
在父組件設置監(jiān)聽事件,監(jiān)聽子組件傳值,也可以用vuex實現(xiàn)
<top v-on:listenToChildEvent="setBackground"></top>
子組件設置數(shù)據(jù)
data() {
return {
uploadFile: {
dialogVisible: false,
uploadImageList: [],
uploadMedia: []
},
dialogFormVisible: false
}
},
點擊彈出圖片上傳界面
<el-tooltip class='item' effect='dark' content='背景圖片設置' placement='bottom'>
<div style="font-size: 14px;margin-right: 20px" @click='dialogFormVisible = true'>
背景設置
</div>
</el-tooltip>
綁定數(shù)據(jù)
<el-dialog v-dialogDrag :visible.sync="dialogFormVisible" width="40%" title="背景圖片設置">
<div style="text-align: center;margin-bottom: 10px">
<span>多張圖片隔10分鐘切換</span>
</div>
<el-upload style="text-align: center" action="你的上傳圖片接口" list-type="picture-card" ref="uploadImages" :multiple="true" :limit="4"
:file-list="uploadFile.uploadImageList" :autoUpload="true" :on-remove="handleUploadRemove" :onPreview="handlePictureCardPreview"
:onSuccess="handleUploadSuccess" :onExceed="()=>{$message.error('背景圖片不能超過四張')}">
<i class="el-icon-plus"></i>
</el-upload>
<div style="text-align: center;margin-top: 10px">
<el-button type="primary" @click='saveImage'>保存</el-button>
</div>
</el-dialog>
handleUploadSuccess(response, file, fileList) { // 上傳圖片成功后的回調
this.uploadFile.uploadImageList = fileList
this.$message.success('上傳成功')
console.log('上傳圖片回調')
},
handleMidiaUploadSuccess(response, file, fileList) { // 上傳媒體成功后的回調
this.uploadFile.uploadMedia = fileList
},
handleUploadRemove(file, fileList) { // 刪除圖片callback
this.uploadFile.uploadImageList = fileList
},
handleMediaRemove(response, file, fileList) {
this.uploadFile.uploadMedia = fileList
},
handlePictureCardPreview(file) { // 預覽圖片
this.uploadFile.dialogImageUrl = file.url
this.uploadFile.dialogVisible = true
},
點擊保存按鈕后觸發(fā)的事件,這時父組件能接收到uploadImageList
saveImage() {
this.$emit('listenToChildEvent', this.uploadFile.uploadImageList)
this.dialogFormVisible = false
},
父組件修改背景圖片的值,并將圖片連接存入localStorage,這樣頁面刷新圖片不會丟失
setData() {
console.log(this.urlList.length)
var imageMax = this.urlList.length - 1
var imageMin = 0
var imageNumber = parseInt(Math.random() * (imageMax - imageMin + 1) + imageMin)
this.url = this.urlList[imageNumber]
console.log(imageNumber)
console.log(this.url)
},
setBackground(data) {
console.log(data)
if (data.length === 0) {
this.url = ''
this.urlList = []
localStorage.setItem('mydata', JSON.stringify(this.urlList))
} else {
this.url = ''
this.urlList = []
for (let i = 0; i < data.length; i++) {
this.urlList.push(
data[i].response.data
)
}
this.setData()
localStorage.setItem('mydata', JSON.stringify(this.urlList))
}
}
頁面初始化的時候從localStorage取數(shù)據(jù)
創(chuàng)建線程每隔10分鐘更換背景圖片
mounted() {
? ? ? this.timer = setInterval(this.setData, 600000)
? ? ? var imgList = JSON.parse(localStorage.mydata)
? ? ? this.urlList = imgList
? ? ? this.setData()
? ? },頁面被銷毀時觸發(fā)事件,清空定時器
beforeDestroy() {
? ? ? clearInterval(this.timer)
? ? ? this.timer = null
? ? },這樣寫完,圖片改變時頁面會閃爍
在設置背景圖片的div上,加上v-cloak 防止頁面閃爍
<div v-cloak class="pull-height animated" :class="{'zoomOutUp': isLock}" :style="{backgroundImage:'url('+url+')'}" style="background-size: 100% 100%">
</div>在style里配置
[v-cloak] {
? ? display: none;
? }element自定義背景更換
最近的項目中需要自定義背景更換。可以在element官網(wǎng)查看使用方法,有2中方法,使用了第一種比較簡單的,第二種自己嘗試了開頭沒有繼續(xù)。

在這里使用這個方法,在項目中新建一個js文件,并且全局引用

在這個element-variables.scss里面內(nèi)容可以官網(wǎng)復制過來
/* theme color */
$--color-primary: #1890ff;
$--color-success: #13ce66;
$--color-warning: #ffba00;
$--color-danger: #ff4949;
$--color-info: rgba(32, 37, 57, 1);
$--button-font-weight: 400;
// $--color-text-regular: #1f2d3d;
$--border-color-light: #dfe4ed;
$--border-color-lighter: #e6ebf5;
$--table-border:1px solid#dfe6ec;
/* icon font path, required */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";
// the :export directive is the magic sauce for webpack
// https://www.bluematador.com/blog/how-to-share-variables-between-js-and-sass
:export {
theme: $--color-primary;
}
我們使用store來實現(xiàn)主題更換

引入index.js里面

此后進行組件編寫在components

<template>
<el-color-picker v-model="defaultColor"
:predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
class="theme-picker"
popper-class="theme-picker-dropdown" />
</template>
<script>
export default {
data () {
return {};
},
props: ['theme'],
computed: {
defaultColor: {
get () {
return this.theme
},
set (val) {
this.$emit('change', val)
}
}
},
methods: {}
};
</script>
<style>
.theme-message,
.theme-picker-dropdown {
z-index: 99999 !important;
}
.theme-picker .el-color-picker__trigger {
height: 26px !important;
width: 26px !important;
padding: 2px;
}
.theme-picker-dropdown .el-color-dropdown__link-btn {
display: none;
}
</style>
以上這里方法是自己寫的,如果是簡單的背景更換,可以使用這個一版本方法,可以看懂的自己研究一下里面方法,例如:
<template>
<el-color-picker
v-model="theme"
:predefine="['#409EFF', '#1890ff', '#304156','#212121','#11a983', '#13c2c2', '#6959CD', '#f5222d', ]"
class="theme-picker"
popper-class="theme-picker-dropdown"
/>
</template>
<script>
const version = require('element-ui/package.json').version // element-ui version from node_modules
// 默認顏色
const ORIGINAL_THEME = '#409EFF' // default color
export default {
data() {
return {
chalk: '', // content of theme-chalk css
theme: ''
}
},
computed: {
defaultTheme() {
return this.$store.state.settings.theme
}
},
watch: {
defaultTheme: {
handler: function(val, oldVal) {
this.theme = val
},
immediate: true
},
async theme(val) {
await this.setTheme(val)
}
},
created() {
if(this.defaultTheme !== ORIGINAL_THEME) {
this.setTheme(this.defaultTheme)
}
},
methods: {
async setTheme(val) {
const oldVal = this.chalk ? this.theme : ORIGINAL_THEME
if (typeof val !== 'string') return
const themeCluster = this.getThemeCluster(val.replace('#', ''))
const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
const getHandler = (variable, id) => {
return () => {
const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
const newStyle = this.updateStyle(this[variable], originalCluster, themeCluster)
let styleTag = document.getElementById(id)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.setAttribute('id', id)
document.head.appendChild(styleTag)
}
styleTag.innerText = newStyle
}
}
if (!this.chalk) {
const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
await this.getCSSString(url, 'chalk')
}
const chalkHandler = getHandler('chalk', 'chalk-style')
chalkHandler()
const styles = [].slice.call(document.querySelectorAll('style'))
.filter(style => {
const text = style.innerText
return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
})
styles.forEach(style => {
const { innerText } = style
if (typeof innerText !== 'string') return
style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
})
this.$emit('change', val)
},
updateStyle(style, oldCluster, newCluster) {
let newStyle = style
oldCluster.forEach((color, index) => {
newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
})
return newStyle
},
getCSSString(url, variable) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
resolve()
}
}
xhr.open('GET', url)
xhr.send()
})
},
getThemeCluster(theme) {
const tintColor = (color, tint) => {
let red = parseInt(color.slice(0, 2), 16)
let green = parseInt(color.slice(2, 4), 16)
let blue = parseInt(color.slice(4, 6), 16)
if (tint === 0) { // when primary color is in its rgb space
return [red, green, blue].join(',')
} else {
red += Math.round(tint * (255 - red))
green += Math.round(tint * (255 - green))
blue += Math.round(tint * (255 - blue))
red = red.toString(16)
green = green.toString(16)
blue = blue.toString(16)
return `#${red}${green}${blue}`
}
}
const shadeColor = (color, shade) => {
let red = parseInt(color.slice(0, 2), 16)
let green = parseInt(color.slice(2, 4), 16)
let blue = parseInt(color.slice(4, 6), 16)
red = Math.round((1 - shade) * red)
green = Math.round((1 - shade) * green)
blue = Math.round((1 - shade) * blue)
red = red.toString(16)
green = green.toString(16)
blue = blue.toString(16)
return `#${red}${green}${blue}`
}
const clusters = [theme]
for (let i = 0; i <= 9; i++) {
clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
}
clusters.push(shadeColor(theme, 0.1))
return clusters
}
}
}
</script>
<style>
.theme-message,
.theme-picker-dropdown {
z-index: 99999 !important;
}
.theme-picker .el-color-picker__trigger {
height: 26px !important;
width: 26px !important;
padding: 2px;
}
.theme-picker-dropdown .el-color-dropdown__link-btn {
display: none;
}
</style>
背景和字體顏色如果是同一個顏色,會有沖突,所以字體顏色需要單獨設置

這里我只是簡單介紹使用方法。如果正式一點自己可以嘗試做成這樣的


以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue學習筆記之指令v-text && v-html && v-bind詳解
這篇文章主要介紹了vue學習筆記之指令v-text && v-html && v-bind詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式
這篇文章主要介紹了vscode+vue cli3.0創(chuàng)建項目配置Prettier+eslint方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

