vue创建自定义插件,message弹窗(toast)

插件介绍

自定义一个可以接受数据的模板用作mseage的弹窗组件,比如点击一个按钮会出现这种提示的组件。
在这里插入图片描述
将这个组件变为一个插件,可以通过类似$store来使用的插件。
比如在某个组件调用这个插件可以使用$toast.show(mesage,timeout)的方式使用。

要完成这个功能需要用到vue的extend和use的方法。

插件实施完整步骤

创建对应弹窗模板

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

<script>

export default {
  name: 'Toast',
  data () {
    return {
      message: '',
      isShow: false // 默认为不显示弹窗
    }
  },
  methods: {
  // 定义一个方法,这样子可以通过.show的方式来调养这个方法,方法接收两个参数,弹窗内容和消失时间
    show (message, time = 1500) {
    // 如果调用了这个方法,就将isShow变成true,也就是显示弹窗
      this.isShow = true
      // 显示弹窗信息
      this.message = message
      // 做一个定时器,定时器的作用就是让弹窗显示一段时间后消失,也就是将isShow 和message在前面的存储的状态还原最初
      setTimeout(() => {
        this.isShow = false
        this.message = ''
        // 传入的显示时间
      }, time)
    }
  },
}

</script>
<style  scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 10px;
}
</style>

创建将toastt组件上的html页面挂载到需要用到$toast的页面上,也就是一个js文件

// 导入刚才创建好的组件
import Toast from './Toast'
//Vue.use(toast),使用use方法会执行install,在这里创建一个空对象
const obj = {}
obj.install = function (Vue) {
  // console.log('一开始就执行了install', Vue)
  // 1.创建组件构造器
  const toastContrustor = Vue.extend(Toast)
  // 2.new方式根据组件构造器,可以创建出来一个组件对象
  const toast = new toastContrustor()
  // 3. 将组件对象手动挂载到某一个元素里面
  toast.$mount(document.createElement('div'))
  // 4.toast.$el对应的就是div
  document.body.appendChild(toast.$el)
  // 1-4步的作用是将Toast组件上的html页面挂载到需要用到$toast的页面上
  // 使用prototype将这个toast赋予成为vue的实例
  Vue.prototype.$toast = toast
}
// 导出这个obj
export default obj

将toast挂载到vue上面,在main.js上进行

import Vue from 'vue'
import App from './App.vue'
// 导入刚才写好的index.js
import toast from 'components/common/toast/index.js'
Vue.config.productionTip = false

// 安装toast插件
Vue.use(toast)

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

在一个界面上使用自定义好的插件

<template>
  <div class="home">
      <button @click="click">按钮</button>
  </div>
</template>
  
<script>
export default {
  name: 'home',
  data () {
    return {
    }
  },
  methods: {
    click () {
      this.$toast.show('弹出的消息', 1500)
    }
  }
}

  </script>
  <style scoped>
.wrapper {
  height: 150px;
  background: red;
}
</style>

效果:
在这里插入图片描述
至此完成自定义message消息弹窗插件(toast)的功能。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值