vue封装toast插件

代码是跟着coderwhy王红元老师的视频打的,这里主要是记录一下

**说明:**想要的效果:监听事件的点击,调用一个method,method中再调用this.$toast.show(message,duration),其中message为提示语,duration为提示语的显示时长

步骤(以下步骤非严格步骤顺序,太麻烦就直接整个文件代码放上来了):

1. 创建一个components文件夹,其中包含两个文件,index.js和toast.vue
2. 编辑toast.vue组件的样式

<template>
  <div class="toast" v-show="isShow">
    <div>{{message}}</div>
  </div>
</template>
  
  <script>
export default {
  name: "Toast",
  data() {
    return {
      message: "",
      isShow: false
    };
  },
  methods: {
    show(message, duration) {
      (this.isShow = true),
        (this.message = message),
        setTimeout(() => {
          (this.isShow = false), (this.message = " ");
        }, duration);
    }
  }
};
</script>
  
<style>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background-color: rgba(0, 0, 0, 0.75);
  padding: 8px 10px;
  color: white;
  border-radius: 5px;
  z-index: 9999;
}
</style>
 

3. 编辑main.js

import Vue from 'vue'
import App from './App.vue'
// 默认导入index.js
import Toast from 'components/common/toast';

Vue.config.productionTip = false

// 安装插件
Vue.use(Toast);//会默认执行install函数

new Vue({
  render: h => h(App)
}).$mount('#app')

4. 编辑index.js文件

import Toast from "./Toast"

const toast = {}

// 当main.js中Vue.use(Toast)后会默认执行install函数,并且会默认传入一个参数Vue
toast.install = function(Vue){
  
// 1.创建组件构造器
const toastConstructor = Vue.extend(Toast)

// 2.根据组件构造器创建一个组件对象
const toast = new toastConstructor()

//3.把toast组件对象挂载到新的元素div中
toast.$mount(document.createElement('div'))

// 4.toast.$el对应的就是div 
document.body.appendChild(toast.$el)

// 在原型中定义$toast
Vue.prototype.$toast = toast;
}

export default toast

5. 使用toast,监听事件执行函数

<template>
  <div class="detail">
    <button @addToCart="addToCart"></button>
  </div>
</template>

<script>
export default {
  name: "Detail",
  methods: {
    addToCart() {
  this.$toast.show("加入购物车成功",2000)
    }
  }
};
</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值