element-ui 背景图片设置
初学vue 看到其他网址都有些背景图片,于是试着自己也写了一下,表述不好请见谅
实现效果
以下是如何实现:
找到你想要设置背景图片的页面
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
在父组件设置监听事件,监听子组件传值,也可以用vuex实现
<top v-on:listenToChildEvent="setBackground"></top>
子组件设置数据
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>
绑定数据
<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 },
点击保存按钮后触发的事件,这时父组件能接收到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取数据
创建线程每隔10分钟更换背景图片
mounted() { this.timer = setInterval(this.setData, 600000) var imgList = JSON.parse(localStorage.mydata) this.urlList = imgList this.setData() },
页面被销毁时触发事件,清空定时器
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官网查看使用方法,有2中方法,使用了第一种比较简单的,第二种自己尝试了开头没有继续。
在这里使用这个方法,在项目中新建一个js文件,并且全局引用
在这个element-variables.scss里面内容可以官网复制过来
/* 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来实现主题更换
引入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>
背景和字体颜色如果是同一个颜色,会有冲突,所以字体颜色需要单独设置
这里我只是简单介绍使用方法。如果正式一点自己可以尝试做成这样的
以上为个人经验,希望能给大家一个参考,也希望大家多多支持阿兔在线工具。