组件封装

本文章以封装toast组件为例(文章最后附有组件代码)

1.新建index.js文件

在对应组件的目录下新建index.js文件,添加代码如下

// 引入想要封装的组件
import Toast from "./Toast";

const obj = {};

obj.install = function(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);

    // 5.将toast添加到原型中
    Vue.prototype.$toast = toast;
}

export default obj

2.安装插件

在第一步中已经完成了封装,现在要安装封装好的插件,在main.js添加如下代码:
在这里插入图片描述

3.使用

this.$toast.方法名称

例如:this.$toast.show(res, 2000);

最后,附上封装的组件内的代码(文件名称: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.message = message;
      this.isShow = true;
      setTimeout(() => {
        this.message = "";
        this.isShow = false;
      }, duration);
    },
  },
};
</script>
<style scoped>
.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.75);
  padding: 10px 20px;
  z-index: 999;
  color: white;
  border-radius: 5px;
  font-size: 20px;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值