1. 程式人生 > 其它 >vue封裝自定義toast

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