VUE Toast封装-插件方式的封装

一.先创建一个toast文件,里面再创建一个toast.vue和一个index.js

toast.vue

<template>
<div class="toast"  v-show="isShow">
<div>{{message}}</div>
</div>
</template>

<script>
export default {
props:{
},
data() {
  return {
    message:'',
    isShow:false
  }
},
methods: {
  show(message,duration){
    this.isShow = true;
    this.message = message

    setTimeout(()=>{
   this.isShow = false;
   this.message =''
    },duration)
  }
},
}
</script>

<style scoped>
.toast{
  width: 200px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  position: fixed;
  font-size: 20px;
  top: 30%;
  left: 50%;
  z-index: 1000;
  color: #ffffff;
  background: rgba(0, 0, 0, .7);
  padding: 10px;
  transform: translate(-50%,-50%)
}
</style>

index.js

import Toast from '../toast/toast.vue'(地址可能不一样,根据自己路径)
const obj ={}

obj.install =function(Vue){
 const toastContrustor = Vue.extend(Toast)

 const toast = new toastContrustor()

 toast.$mount(document.createElement('div'))

 document.body.appendChild(toast.$el)

  Vue.prototype.$toast =toast
}
export default obj

二.在main.js中用引入插件的方式引入

import toast from './components/common/toast'(地址可能不一样,根据自己路径)
Vue.use(toast)

三.在页面进行使用

  this.$toast.show(content,time)
 - content:你要显示的内容
 - time:多长时间消失
 示例:
 this.$toast.show('您太棒了',1000)
发布了53 篇原创文章 · 获赞 76 · 访问量 1708

猜你喜欢

转载自blog.csdn.net/weixin_45389051/article/details/104668168