将组件封装成插件

(一) 创建组件

在src/components/Toash.vue文件中,创建一个组件

<template>
  <div class="toast" v-show="isShow">
      <h2 style="color: red;">{{message}}</h2>
  </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;
      }, duration);
    },
  },
};
</script>

(二) 将组件封装为插件

将组件封装在自己创建的 src/myPlugin.js 文件中

import Toast from "./components/Toash";

const obj = {};
//参数Vue是install自带的,而且就是Vue
obj.install = function (Vue) {
  //1. 创建组件构造器
  const toastConstruct = Vue.extend(Toast);
  // 2. new的方式,根据组件构造器,可以创建一个组件对象
  const toast = new toastConstruct();
  // 3.将组件对象,手动挂着到某一个元素上
  toast.$mount(document.createElement('div'));
  // 4.toast.$el对应的就是div
  document.body.appendChild(toast.$el)
  Vue.prototype.$toast = toast;
}
export default obj;

(三) 应用插件

在src/main.js注册插件

import MyPlugin from "./myPlugin.js";
//.....
Vue.use(MyPlugin);
//....

(四) 使用插件

在另一个组件中调用插件的show方法, 其中显示的“调用”文字将在1.5s后被隐藏

export default {
	//...
  mounted() {
    this.$toast.show('调用', 1500);
  },
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值