封装$toast组件挂着在vue上

参考:https://www.jb51.net/article/159958.htm

1. 创建myInfo文件夹:包括index.js和index.vue文件。

    1.1 在index.vue中:

<template>
  <div class="my_info">
    <p class="text">{{content}}</p>
  </div>
</template>
<script>
export default {
  data(){
      return{
          type: "",
          content:'',
          timer:2000
      }
  },
  mounted() {
    setTimeout(() => {   
      this.$el.parentNode.removeChild(this.$el); // 3s 后通过父级移除子元素的方式来移除该组件
    }, this.timer);
  }
};
</script>
<style lang="less" scoped>
.my_info {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  color: #fff;
  z-index: 9999;
  background: transparent;
  .text {
    padding: 18px 24px;
    max-width: 500px;
    font-size: 16px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0.8);
  }
}
</style>

    1.2 在index.js中:

import Vue from "vue"; // 引入 Vue 是因为要用到 Vue.extend() 这个方法
import index from "./index.vue"; // 引入刚才的 toast 组件
 
let ToastConstructor = Vue.extend(index); // 这个在前面的前置知识内容里面有讲到
let instance;
 
const MyToast = function(options = {}) {
 instance = new ToastConstructor({
    data: options   // 这里的 data 会传到 main.vue 组件中的 data 中,当然也可以写在 props 里
 }); // 渲染组件
  document.body.appendChild(instance.$mount().$el); // 挂载到 body 下
};
export default MyToast;

    1.3 在vue项目的入口文件main.js中:

import Vue from 'vue'
import MyToast from "@/components/myInfo/index.js"
Vue.prototype.$MyToast = MyToast;

    1.4 在vue其他组件中调用:

this.$MyToast({
	content:'传参错误,请检查!'
})
发布了200 篇原创文章 · 获赞 37 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42231156/article/details/103374427