首頁 > 軟體

在vue中使用screenfull 依賴,實現全螢幕元件方式

2022-12-09 14:02:10

vue使用screenfull依賴,實現全螢幕元件

需求:將頁面全螢幕化,實現按F11全螢幕的效果

實現:

1.下載screenfull依賴

npm install --save screenfull

2.在components資料夾下封裝一個全螢幕元件FullScreen

 index.vue程式碼如下,直接cv就可以使用

<template>
  <div class="full-screen-wrapper" @click="handleFullscreen">
    <el-tooltip
      effect="dark"
      :content="isFullscreen ? '退出全螢幕' : '全螢幕'"
      placement="bottom"
    >
      <i
        :class="[
          'icon',
          !isFullscreen
            ? 'vue-dsn-icon-fullscreen'
            : 'vue-dsn-icon-tuichuquanping',
        ]"
      />
    </el-tooltip>
  </div>
</template>
 
<script>
import screenfull from "screenfull";
 
export default {
  name: "FullScreen",
  data() {
    return {
      isFullscreen: false,
    };
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.destroy();
  },
  methods: {
    handleFullscreen() {
      if (screenfull.enabled) {
        this.$message({
          message: "不支援全螢幕!",
          type: "warning",
        });
        return false;
      }
      screenfull.toggle();
    },
    change() {
      this.isFullscreen = screenfull.isFullscreen;
    },
    init() {
      if (!screenfull.enabled) {
        screenfull.on("change", this.change);
      }
    },
    destroy() {
      if (!screenfull.enabled) {
        screenfull.off("change", this.change);
      }
    },
  },
};
</script>
 
<style lang="less">
.full-screen-wrapper {
  float: left;
  width: 22px;
  height: 22px;
  padding: 4px;
  cursor: pointer;
 
  .icon {
    font-size: 24px;
  }
 
  &:hover {
    color: #409eff;
  }
}
</style>

在哪裡需要呼叫這個元件,就可以通過元件呼叫的方式來直接呼叫

vue使用Screenfull全螢幕切換

1.在終端執行命令 npm install --save screenfull

2.在components檔案中建立Screenfull檔案裡面的程式碼如下

<template>
  <div>
    <svg-icon :icon-class="isFullscreen?'exit-fullscreen':'fullscreen'" @click="click" />
  </div>
</template>

<script>
import screenfull from 'screenfull'

export default {
  name: 'Screenfull',
  data() {
    return {
      isFullscreen: false
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.destroy()
  },
  methods: {
    click() {
      if (!screenfull.enabled) {
        this.$message({
          message: 'you browser can not work',
          type: 'warning'
        })
        return false
      }
      screenfull.toggle()
    },
    change() {
      this.isFullscreen = screenfull.isFullscreen
    },
    init() {
      if (screenfull.enabled) {
        screenfull.on('change', this.change)
      }
    },
    destroy() {
      if (screenfull.enabled) {
        screenfull.off('change', this.change)
      }
    }
  }
}
</script>

<style scoped>
.screenfull-svg {
  display: inline-block;
  cursor: pointer;
  fill: #5a5e66;;
  width: 20px;
  height: 20px;
  vertical-align: 10px;
}
</style>

3.在需要的用的頁面引入我們的Screenfull檔案

4.頁面的使用方法

總結

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


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