Vue之简易弹窗组件

古城微笑少年丶 2022-12-03 09:14 301阅读 0赞

组件模板
Notice.vue

  1. <template>
  2. <div class="box" v-if="isShow">
  3. <h3>{ { title}}</h3>
  4. <p class="box-content">{ { message}}</p>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. props: {
  10. title: {
  11. type: String,
  12. default: ""
  13. },
  14. message: {
  15. type: String,
  16. default: ""
  17. },
  18. duration: {
  19. type: Number,
  20. default: 1000
  21. }
  22. },
  23. data() {
  24. return {
  25. isShow: false
  26. };
  27. },
  28. methods: {
  29. show() {
  30. this.isShow = true;
  31. setTimeout(this.hide, this.duration);
  32. },
  33. hide() {
  34. this.isShow = false;
  35. this.remove();
  36. }
  37. }
  38. };
  39. </script>
  40. <style>
  41. .box {
  42. position: fixed;
  43. width: 100%;
  44. top: 16px;
  45. left: 0;
  46. text-align: center;
  47. pointer-events: none;
  48. background-color: #fff;
  49. border: grey 3px solid;
  50. box-sizing: border-box;
  51. }
  52. .box-content {
  53. width: 200px;
  54. margin: 10px auto;
  55. font-size: 14px;
  56. padding: 8px 16px;
  57. background: #fff;
  58. border-radius: 3px;
  59. margin-bottom: 8px;
  60. }
  61. </style>

创建组件实例
create.js

  1. import Vue from "vue";
  2. // 传递一个组件配置,返回一个组件实例,并且挂载它到body上
  3. function create(Component, props) {
  4. // 组件实例创建
  5. const Ctor = Vue.extend(Component);
  6. const comp = new Ctor({ propsData: props})
  7. comp.$mount()
  8. // dom追加
  9. document.body.appendChild(comp.$el)
  10. // 获取组件实例
  11. comp.remove = () => {
  12. document.body.removeChild(comp.$el)
  13. comp.$destroy()
  14. }
  15. return comp
  16. }
  17. export default create;

编写插件,挂载到vue原型上,便于全局调用
notice.js

  1. import Notice from "../components/Notice.vue"
  2. import create from "../utils/create"
  3. export default {
  4. install(Vue){
  5. Vue.prototype.$notice = function(options){
  6. create(Notice,options).show();
  7. }
  8. }
  9. }

main.js引入使用

  1. import notice from './plugins/notice.js'
  2. Vue.use(notice)

组件内调用

  1. this.$notice({
  2. title: "请求成功",
  3. message: "成功",
  4. duration: 3000,
  5. })

效果展示
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,301人围观)

还没有评论,来说两句吧...

相关阅读