vue封装自定义toast

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vue封装自定义toast脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

封装自定义toast:

 

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

@H_406_10@

 

 

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 />快去微信分享给好友吧!')

 

脚本宝典总结

以上是脚本宝典为你收集整理的vue封装自定义toast全部内容,希望文章能够帮你解决vue封装自定义toast所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。