照片展示屏轮播(页面自适应 axios请求数据 websocket更新数据)

259 阅读1分钟

效果图如下 5s变动一次

实际项目不是这样的我另外替换了图片,右上角的恐龙是不动的

GIF.gif

首先看一下整体文件结构

image.png

首先在App.vue中设置好页面自适应

<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>

export default {
  mounted() {
    this.autofit();
    window.onresize = this.autofit
    
  },
  methods: {
    autofit() {
      const width = document.documentElement.clientWidth;
      const height = document.documentElement.clientHeight;
      const w = 1920; //设计稿规定分辨率
      const H = 1080;
      const scalew = width / w;
      const scaleH = height / H;
      // console.log(width, height);
      // console.log(scalew, scaleH);
      const scale = scalew > scaleH ? scaleH : scalew;
      const $app = document.getElementById("app");
      $app.style.transform =`scale(${scale})`
      $app.style.transformOrigin = "0% 0%";
      $app.style.position = "absolute";
      if (scalew > scaleH) {
        $app.style.left = `${(width - scale * w) / 2}px`;
      } else {
        $app.style.top = `${(height - scale * H) / 2}px`;
      }
    },
  },
};
</script>
<style lang="less">

html,
body {
  margin: 0px;
  overflow: hidden;
  background-color: black;
}

#app {
  width: 1920px;//设计稿规定分辨率
  height: 1080px;
  padding: 0px;
  margin: 0px;
  overflow: hidden;
  
}

p {
  margin: 0;
}

</style>

在home.vue的代码

因为上传的图片可能是不一样的尺寸 所以再div中添加了 backgroundImage 进行了路径拼接

<template>
  <div class="screen-container">
    <div class="content">
      <div
        :style="{
          backgroundImage: 'url(' + ip + item.imgurl + ')',
          backgroundRepeat: 'no-repeat',
          backgroundSize: 'cover',
        }"
        class="imgBox"
        v-for="item in topFiveData"
        :key="item._id"
      ></div>
    </div>

    <div class="rightCode">
      <img src="../../public/img/rightBg.png" />
    </div>
  </div>
</template>

引入axios获取数据 引入config里面有配置好的ip地址在不同环境中切换

这里看一下config.js

const env = process.env.NODE_ENV
let ip = 'localhost'

if (env === 'production') {
    ip = '192.168.3.72'
}

export default {
    env,
    ip,
    HTTP_SERVER: `http://${ip}:8899`,
    WS_SERVER:`ws://${ip}:4001/data`,
}

回到home.vue页面 看下export default里面的结构

image.png

getWS sendMsg都是请求websocket的方法

getWS() {
      this.ws = null;
      const ws = new WebSocket(config.WS_SERVER);
      ws.onopen = () => {
        console.log(`服务端连接成功`);
        //注册
        this.sendMsg({
          action: "REGISTER",
        });
        this.isOpen = true;
      };
      ws.onmessage = (msg) => {
        console.log("接收消息", msg.data);
        const data = JSON.parse(msg.data);
        const action = data.action;
        if (action === "UPDATE") {
          this.initData();//当收到消息是UPDATE时 更新数据
        }
      };
      ws.onerror = (err) => {
        console.log("连接出错", err);
        this.ws = null;
      };
      ws.onclose = () => {
        console.log("断开连接");
        this.ws = null;
        this.isOpen = false;
      };
      this.ws = ws;
    },
    sendMsg(data) {
      if (this.ws) {
        this.ws.send(JSON.stringify(data));
      }
    },

initData 初始化数据 startInteral计时器 change为判断照片改变的方法

initData() {
      axios.get(`${config.HTTP_SERVER}/c/getPhotoforWall`).then(
        (response) => {
          console.log("获取照片成功", response.data.data);
          this.picturesData = response.data.data;
         //当要变动的照片数量小于等于5张时 停止计时器
          if (this.picturesData.length <= 5) {
            clearInterval(this.timerId);
          } else {
            this.startInteral();
          }

          this.topFiveData = this.picturesData.slice(0, 5);
        },
        (error) => {
          console.log("照片数据接收失败", error.message);
        }
      );
      this.topFiveData = this.picturesData.slice(0, 5);
    },
startInteral() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }

      this.timerId = setInterval(() => {
        console.log("计时器");
        this.change();
      }, 5000);
    },
 change() {
      this.topFiveData = [];
      let index = 5;

      if (this.index === this.picturesData.length) {
        this.index = 0;
      }
      for (let i = this.index; i < this.index + 5; i++) {
        if (this.picturesData[i]) {
          this.topFiveData.push(this.picturesData[i]);
          index = i;
        }
      }
      this.index = index + 1;
      // console.log(this.topFiveData);
    },

下面再放上一段图片样式代码

<style scoped lang="less">
.position(@l,@t) {
  position: absolute;
  left: @l;
  top: @t;
}

.screen-container {
  position: relative;
  background: url("../../public/img/bj.png");
  background-color: black;
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  z-index: 0;
  .content {
    & > img:nth-child(1) {
      .position(24px,120px);
    }

    & > img:nth-child(2) {
      .position(656px,120px);
    }

    & > img:nth-child(3) {
      .position(24px,600px);
    }

    & > img:nth-child(4) {
      .position(656px,600px);
    }

    & > img:nth-child(5) {
      .position(1288px,600px);
    }
  }

  .imgBox {
    width: 608px;
    height: 456px;
    z-index: 1;
  }

  .rightCode {
    & > img:nth-child(1) {
      .position(1285px,117px);
      z-index: 1;
    }

    & > img:nth-child(2) {
      .position(1336px,213px);
      z-index: 2;
    }

    & > img:nth-child(3) {
      .position(1631px,213px);
      z-index: 1;
    }
  }
}
</style>

最新又改了需求,要求:可以滚动的照片 能被5整除时,页面滚动。 如果不能被整除,就单张滚动

比如 有图片数据 [1,2,3,4,5,6,7,8]

初始展示: 第一页 [1,2,3,4,5] 第二页[6,7,8]

第一次滚动: 第一页 [8,1,2,3,4] 第二页[5,6,7]

第二次滚动: 第一页 [7,8,1,2,3] 第二页[4,5,6]

change() {
      //能被5整除
      if (this.picturesData.length % 5 == 0) {
        this.topFiveData = [];
        let index = 5;
        //当index的值等于数组长度 就返回第一个
        if (this.index === this.picturesData.length) {
          this.index = 0;
        }
        for (let i = this.index; i < this.index + 5; i++) {
          if (this.picturesData[i]) {
            this.topFiveData.push(this.picturesData[i]);
            index = i;
          }
        }
        this.index = index + 1;
        console.log(this.topFiveData);
      }

      //不能被5整除
      if (this.picturesData.length % 5 != 0) {
        this.picturesData.map((item, index) => {
          if (index == this.picturesData.length - 1) {
            this.picturesData.unshift(this.picturesData.splice(index, 1)[0]);
          }
        });
        this.topFiveData = this.picturesData.slice(0, 5);
        console.log(this.picturesData);
      }
    },