当前位置:Gxlcms > JavaScript > Vue组件教程之Toast(Vue.extend 方式)详解

Vue组件教程之Toast(Vue.extend 方式)详解

时间:2021-07-01 10:21:17 帮助过:4人阅读

一、效果图

二、说明

这类提示框组件我们通常都会直接在 JS 代码中进行调用。像下面这样:

  1. this.$toast('别点啦,到头啦!')

但看到网上大多数还是通过 component 方式实现的,这样的话我们在使用的时候还要在 DOM 中放置一个组件元素,然后通过一个变量来控制它的显示隐藏,这样使用起来非常的不方便。那么有什么方法可以不用在 DOM 中手动放置组件元素就可以直接调用呢?答案就是 Vue.extend。通过 Vue.extend 方式实现的组件,需要两个文件,一个是 .vue 文件,另外一个就是管理 .vue 的 .js 文件。具体代码如下:

三、代码

Toast.vue 文件代码

  1. <template>
  2. <div class="toast" v-show="visible">
  3. {{ message }}
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'toast',
  9. data () {
  10. return {
  11. message: '', // 消息文字
  12. duration: 3000, // 显示时长,毫秒
  13. closed: false, // 用来判断消息框是否关闭
  14. timer: null, // 计时器
  15. visible: false // 是否显示
  16. }
  17. },
  18. mounted () {
  19. this.startTimer()
  20. },
  21. watch: {
  22. closed (newVal) {
  23. if (newVal) {
  24. this.visible = false
  25. this.destroyElement()
  26. }
  27. }
  28. },
  29. methods: {
  30. destroyElement () {
  31. this.$destroy()
  32. this.$el.parentNode.removeChild(this.$el)
  33. },
  34. startTimer () {
  35. this.timer = setTimeout(() => {
  36. if (!this.closed) {
  37. this.closed = true
  38. clearTimeout(this.timer)
  39. }
  40. }, this.duration)
  41. }
  42. }
  43. }
  44. </script>
  45. <style lang="scss" scoped>
  46. .toast {
  47. position: fixed;
  48. bottom: 15vh;
  49. left: 28vw;
  50. min-width: 40vw;
  51. max-width: 100vw;
  52. font-size: 26px;
  53. text-align: center;
  54. padding: 10px 2vw;
  55. border-radius: 40px;
  56. background-color: rgba(0, 0, 0 , 0.6);
  57. color: rgb(223, 219, 219);
  58. letter-spacing: 3px;
  59. }
  60. </style>

Toast.js 文件代码

  1. import Vue from 'vue'
  2. import Toast from '@/components/layer/Toast.vue'
  3. let ToastConstructor = Vue.extend(Toast) // 构造函数
  4. let instance // 实例对象
  5. let seed = 1 // 计数
  6. const ToastDialog = (options = {}) => {
  7. if (typeof options === 'string') {
  8. options = {
  9. message: options
  10. }
  11. }
  12. let id = `toast_${seed++}`
  13. instance = new ToastConstructor({
  14. data: options
  15. })
  16. instance.id = id
  17. instance.vm = instance.$mount()
  18. document.body.appendChild(instance.vm.$el)
  19. instance.vm.visible = true
  20. instance.dom = instance.vm.$el
  21. instance.dom.style.zIndex = 999 + seed
  22. return instance.vm
  23. }
  24. export default ToastDialog

四、使用

首先在 main.js 中引入 Toast.js 并挂载到vue原型上,如下图:

其次,在代码中使用

  1. this.$toast('别点啦,到头啦!')

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

人气教程排行