vue封装自定义toast

封装自定义toast:

1、新建toast文件夹,文件夹内新建toast.vue和index.js文件:

2、toast.vue代码:

<template>
    <transition name="fade">
        <div class="toast" v-show="show" v-html="message"><!-- 使用v-html,展示多样化样式内容 -->
            <!-- {{message}} --><!-- 若仅展示固定样式文本,使用此方式 -->
        </div>

    </transition>
</template>

<script>
    export default {
        data() {
            return {
                show: false,
                message: "",
            }
        }
    }
</script>

<style lang="scss" scoped>
.toast {
  position: fixed;
  top: 40%;
  left: 50%;
  margin-left: -100px;
  padding: 2vw;
  width: 200px;
  font-size: 1rem;
  line-height: 1.75rem;
  color: #fff;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 5px;
  z-index: 999;
}

.fade-enter-active,
.fade-leave-active {
  transition: 0.3s ease-out;
}
.fade-enter {
  opacity: 0;
  transform: scale(1.2);
}
.fade-leave-to {
  opacity: 0;
  transform: scale(0.8);
}
</style>

3、index.js代码:

import ToastComponent from './toast.vue'

const Toast = {};

// 注册Toast
Toast.install = function (Vue) {
    // 生成一个Vue的子类
    // 同时这个子类也就是组件
    const ToastConstructor = Vue.extend(ToastComponent)
    // 生成一个该子类的实例
    const instance = new ToastConstructor();

    // 将这个实例挂载在我创建的div上
    // 并将此div加入全局挂载点内部
    instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el)
    
    // 通过Vue的原型注册一个方法
    // 让所有实例共享这个方法 
    Vue.prototype.$toast = (msg, duration = 2000) => {
        instance.message = msg;
        instance.show = true;

        setTimeout(() => {
            
            instance.show = false;
        }, duration);
    }
}

export default Toast

4、在main.js引入全局Toast

import Toast from './components/toast'
Vue.use(Toast)

5、页面使用toast

如若使用v-html模式,下文的<br />换行生效

如若使用{{message}}模式,下文的<br />换行不生效

this.$toast('链接复制成功,<br />快去微信分享给好友吧!')
原文地址:https://www.cnblogs.com/Intellectualscholar/p/15318070.html