基于vue 仿 Element ui 的消息提示组件

717 阅读4分钟

  第一次写,写得不好的地方希望大家见谅啦~

1. 在components 新建文件夹 Message

2. Message中创建文件 Message.vue

<template>
  <div class="main">    
    <button @click="suss">成功</button>    
    <button @click="warn">警告</button>    
    <button @click="mes">消息</button>    
    <button @click="err">错误</button>    
    <msgAlert :arr="arr" :isShow="isShow" />  // 属性传值,注意由父组件向子组件传值
    </div>
</template>

     

import msgAlert from "./msgAlert";
//调用组件
components: { msgAlert },
  data() {
    return { 
     arr: [],    // 定义一个空数组,放各种提示的info,bgcorlor,showClass 
     isShow: false,  
 };  
},  
methods: {  
  suss() {   
   let a = {};   
   this.isShow = true;   //点击button时,触发子组件计时器
   a.info = "这是一条成功的消息";   
   a.bgcorlor = "#8fd3f4";     
   a.showClass = "el-icon-success";  
   this.arr.push(a); // 把消息提示的文字内容,背景颜色,图标追加到arr里     
 },   
 warn() { 
   let a = {};   
   this.isShow = true;  
   a.info = "这是一条警告的消息";   
   a.bgcorlor = "#f9f586";   
   a.showClass = "el-icon-warning";  
    this.arr.push(a);    
    },   
 mes() {      
   let a = {};     
    this.isShow = true;  
    a.info = "这是一条消息的提示信息";  
    a.bgcorlor = "#8ec5fc";    
    a.showClass = "el-icon-info";   
    this.arr.push(a);   
   },   
 err() { 
    let a = {};  
    this.isShow = true; 
    a.info = "这是一条错误的消息";  
    a.bgcorlor = "#74ebd5";    
    a.showClass = "el-icon-error";  
    this.arr.push(a);   
    }, 
 },
<style lang="scss" scoped>
.main {
  text-align: center; // 文字居中
}
button {
  padding: 10px 15px; 
  margin: 100px 10px 0;
  border: none; 
  outline: none; 
  border-radius: 5px;
}
</style>

3.Message中创建子组件 msgAlert.vue

<template>  
<div>    
<div      
class="alter-box"      
v-for="(item,index) in arr"      
:key="index"      
:style="{backgroundColor:item.bgcorlor}"    
>      
<p :class="item.showClass">{{item.info}}</p>    
</div> 
 </div>
</template>

<script>
export default {  
data() { 
   return {  
    time: null,  
      };
  }, 
// 子组件接收父组件传来的值
 props: { 
   arr: {   
   type: Array,  
  },  
  isShow: {  
    type: Boolean, 
   },
  }, 
 watch: {  
// 用watch监听经常需要变动数据
 isShow(val) {   

   if (val) {    
    this.time = setInterval(() => { 
         this.arr.shift();  
        //shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。 
       }, 3000);  // 设置3秒后消息提示消失
 }   
 },  
},  
// 即将离开页面前,销毁监听事件  
destroyed() { 
   clearInterval(this.time);   
 //使用 clearInterval() 来停止计时器执行 
 },
};
</script>
<style>
.alter-box {
  top: 0; 
 right: 0; 
 color: #1f65e6; 
 text-align: center;
  line-height: 50px;
  width: 350px; 
 height: 50px; 
 border: 1px solid #e8e8e8; 
 border-radius: 5px; 
 margin: 10px 0;
}
p {  
padding-left: 20px;
}
</style>

4.最后直接在需要的地方调用父组件就好啦