vue封装公共组件调用方法

需求:项目中所有的提示信息都是弹框样式的,并且显示两秒后自动消失
vue页面

<template>
  <!-- 公用提示信息页面 -->
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    :show-close="false"
    top="40vh"
    width="30%"
  >
    <div class="content">
      <span>{
    
    {
    
     text }}</span>
    </div>
  </el-dialog>
</template>
<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      dialogVisible: true,
      text: ""
    };
  }
};
</script>
<style lang="less" scoped>
.content {
    
    
  font-size: 16px;
  color: #333;
  text-align: center;
  span {
    
    
    margin-left: 10px;
  }
}
/deep/ .el-dialog__header {
    
    
  padding: 0;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-weight: 600;
  background-color: #08519c;
}
/deep/ .el-dialog__title {
    
    
  color: #fff;
}
</style>

js页面

// 公共提示信息js
import Vue from "vue";
import Toast from "./dialogMessage.vue"; //引入组件
// 返回一个“扩展实例构造器”
let ToastConstructor = Vue.extend(Toast);

let myToast = (text, duration) => {
    
    
  let toastDom = new ToastConstructor({
    
    
    el: document.createElement("div") //将toast组件挂载到新创建的div上
  });
  document.body.appendChild(toastDom.$el); //把toast组件的dom添加到body里

  toastDom.text = text;
  toastDom.duration = duration;

  // 在指定 duration 之后让 toast消失
  setTimeout(() => {
    
    
    toastDom.dialogVisible = false;
  }, toastDom.duration);

  // 调用时  this.$toast("新内容", 1000);
};
export default myToast;

在main.js中全局注册

import toast from "./components/dialogMessage.js"; //引入toast函数
  //给Vue对象添加$toast方法
  Vue.prototype.$toast = toast;

页面中使用,像使用message一样

 this.$toast("新内容", 1000);

效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48300785/article/details/124509932
今日推荐