最簡單的vue消息提示全局組件的方法
更新時間:2019年06月16日 11:28:35 作者:渣渣輝
這篇文章主要介紹了最簡單的vue消息提示全局組件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
簡介
實現(xiàn)功能
- 自定義文本
- 自定義類型(默認(rèn),消息,成功,警告,危險)
- 自定義過渡時間
使用vue-cli3.0生成項目


toast全局組件編寫
/src/toast/toast.vue
<template>
<div class="app-toast"
v-if="isShow"
:class="{'info': type=== 'info','success': type=== 'success','wraning': type=== 'wraning','danger': type=== 'danger'}">{{text}}</div>
</template>
<style scoped>
.app-toast {
position: fixed;
left: 50%;
top: 50%;
background: #ccc;
padding: 10px;
border-radius: 5px;
transform: translate(-50%, -50%);
color: #fff;
}
.info {
background: #00aaee;
}
.success {
background: #00ee6b;
}
.wraning {
background: #eea300;
}
.danger {
background: #ee000c;
}
</style>
/src/toast/index.js
import vue from 'vue'
import toastComponent from './toast.vue'
// 組件構(gòu)造器,構(gòu)造出一個 vue組件實例
const ToastConstructor = vue.extend(toastComponent)
function showToast ({ text, type, duration = 2000 }) {
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data () {
return {
isShow: true, // 是否顯示
text: text, // 文本內(nèi)容
type: type // 類型
}
}
})
// 添加節(jié)點
document.body.appendChild(toastDom.$el)
// 過渡時間
setTimeout(() => {
toastDom.isShow = false
}, duration)
}
// 全局注冊
function registryToast () {
vue.prototype.$toast = showToast
}
export default registryToast
全局注冊
/main.js
import toastRegistry from './toast/index' Vue.use(toastRegistry)
調(diào)用
/src/views/home.vue
<template>
<div class="home">
<input type="button"
value="顯示彈窗"
@click="showToast">
</div>
</template>
<script>
export default {
name: 'home',
methods: {
showToast () {
this.$toast({
text: '我是消息'
// type: 'wraning',
// duration: 3000
})
}
}
}
</script>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue中動態(tài)渲染數(shù)據(jù)時使用$refs無效的解決
這篇文章主要介紹了vue中動態(tài)渲染數(shù)據(jù)時使用$refs無效的解決方案,具有很好的參考價值。希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
el-tree樹設(shè)置懶加載以及設(shè)置默認(rèn)勾選方式
這篇文章主要介紹了el-tree樹設(shè)置懶加載以及設(shè)置默認(rèn)勾選方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

