VUE 笔记 ilovecoding 224 Toast封装-插件方式的封装

1. 创建插件

1.1 新增 index.js

在组件的 toast 目录下新增 index.js

const obj = {}

obj.install = function() {
  console.log('要么孤独,要么庸俗。');
}

export default obj

1.2 安装插件

在 main.js 中导入插件并安装

import toast from 'components/common/toast'
// 安装 toast 插件
app.use(toast);

1.3 启动服务

2. 项目代码

2.1 index.js

import { createApp } from 'vue'

import Toast from './Toast'

const obj = {}

obj.install = function(app) {

  const toastAppp = createApp(Toast)
  const instance = toastAppp.mount(document.createElement('div'))
  document.body.appendChild(instance.$el)
  app.config.globalProperties.$toast = instance

}

export default obj

2.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 = 2000) {
      this.isShow = true
      this.message = message

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

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

  color: #fff;
  background-color: rgba(0, 0, 0, .75);
  z-index: 2147483647;
}
</style>

注意:z-index: 2147483647;,没有该属性不会显示弹窗。

2.3 Detail.vue

去掉导入的 Toast.vue 组件,直接使用 this.$toast.show(res, 1500)

      addToCart() {
        // 1. 获取购物车需要展示的信息
        const product = {}
        product.image = this.topImages[0]
        product.title = this.goods.title
        product.desc = this.goods.desc
        product.price = this.goods.realPrice
        product.iid = this.iid
        // 2. 将商品添加到购物车里
        this.addCart(product).then(res => {
          this.$toast.show(res)
        })
      }
posted @ 2023-01-16 21:06  君子键  阅读(34)  评论(0)    收藏  举报