首頁 > 軟體

Vue + element-ui 背景圖片設定方式

2022-08-01 14:00:31

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>

背景和字型顏色如果是同一個顏色,會有衝突,所以字型顏色需要單獨設定

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

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com