使用extend手动封装toast

在项目中实现类似于this.$toast('信息')的组件动态渲染,使用extend构造器动态添加到页面再消失。

toast.vue中写组件的样式代码

<template>
  <div class="container">
    <div class="msgBox" v-if="show">{{msg}}</div>
  </div>
</template>
<script>
export default {
  props:{
//注意:这里一定要注释掉msg,因为msg内容是通过后面函数的参数传递过来的,但是会优先拿default的值,发生错误
// msg:{ // type:String, // default:'hello' // } } } </script> <style scoped> .msgBox{ position: fixed; top:50%; left:50%; padding:5px 20px; border-radius: 3px; background: red; color:white; } .container{ width:100%; height:100%; } </style>

在components文件夹下的toast文件夹中的toast.js:

import toast from "./toast"
import Vue from "vue"

let toastDemo=Vue.extend(toast);

function sendToast(msg,duration=2000){
  let demo=new toastDemo({
    el:document.createElement("div"),
    data(){
      return{
        msg:msg,
        show:true
      }
    }
  })
  document.body.appendChild(demo.$el)
  setTimeout(()=>{
    demo.show=false
  },duration)
}

export default sendToast

在main.js中将其添加到Vue原型对象:

import Vue from "vue"
import toast from "@/components/toast/toast.js"

Vue.prototype.$toast=toast

在组件中使用:

<button @click="sendMsg">显示toast</button>

methods:{
 sendMsg(){
   this.$toast('可以显示啦!',3000);
   //第二个参数可以写显示时长,由于在函数中有默认值,也可以省略
 }
}
posted @ 2020-06-12 14:03  轻染  阅读(262)  评论(0编辑  收藏  举报