1. 程式人生 > 其它 >Vue.extend 編寫 Toast

Vue.extend 編寫 Toast

home.vue

<template>
  <div>
    <el-button @click="toToast"> 顯示 </el-button>
  </div>
</template>

<script>
import { showToast } from "./toast.js";
export default {
  methods: {
    toToast() {
      showToast("測試", 1500);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

toast.js

import Vue  from "vue";
import Toast from './toast.vue'
const ToastCtor=Vue.extend(Toast)
export function showToast(content,delay){
    const toastComp=new ToastCtor().$mount()
    document.body.appendChild(toastComp.$el)
    toastComp.toShow(content)
    setTimeout(() => {
        toastComp.toClose()
        toastComp.$el.parentNode.removeChild(toastComp.$el) 
    }, delay);
}

toast.vue

<template>
  <!-- <div class="toast" v-if="show">{{message}}</div> -->
  <div class="toast" v-show="show">{{message}}</div>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      message:'',
    };
  },
  methods: {
    toShow(content) {
        this.message=content
      this.show = true;
    },
    toClose() {
      this.show = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.toast {
  position: fixed;
  top: 10px;
  left: 50%;
  padding: 10px 20px;
  background: rgba(22, 21, 21, 0.658);
  color: #fff;
  font-size: 14px;
  border-radius: 6px;
  min-width: 80px;
  text-align: center;
}
</style>