VUE 2.x中全局組件的封裝(三)

Vue.extend 屬于 Vue 的全局 API,在實際業(yè)務開發(fā)中我們很少使用,因為相比常用的 Vue.component 寫法使用 extend 步驟要更加繁瑣一些。但是在一些獨立組件開發(fā)場景中,Vue.extend + $mount 這對組合是我們需要去關注的。
用法:
使用基礎 Vue 構(gòu)造器,創(chuàng)建一個“子類”。參數(shù)是一個包含組件選項的對象
data 選項是特例,需要注意 - 在 Vue.extend() 中它必須是函數(shù)

為什么使用 extend

在 vue 項目中,我們有了初始化的根實例后,所有頁面基本上都是通過 router 來管理,組件也是通過 import 來進行局部注冊,所以組件的創(chuàng)建我們不需要去關注,相比 extend 要更省心一點點。但是這樣做會有幾個缺點:

  1. 組件模板都是事先定義好的,如果我要從接口動態(tài)渲染組件怎么辦?
  2. 所有內(nèi)容都是在 #app 下渲染,注冊組件都是在當前位置渲染。如果我要實現(xiàn)一個類似于 window.alert() 提示組件要求像調(diào)用 JS 函數(shù)一樣調(diào)用它,該怎么辦?

這時候,Vue.extend + vm.$mount 組合就派上用場了。

一個簡單示例-hello world

index.vue

<template>
  <div>
    <p>text:{{ text }}</p>
    <p>content:{{ content }}</p>
    <p>isShow:{{ isShow }}</p>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: "textDefault"
    }
  },
  data() {
    return {
      isShow: false,
      content: "contentDefault"
    };
  }
};
</script>

跟他同級目錄的 index.js

import Vue from "vue";
import helloWorld from "./index.vue";
const HelloWorldConstructor = Vue.extend(helloWorld);

const Hello = option => {
  const HelloWorldInstance = new HelloWorldConstructor({
    data: {
      content: option.content
    },
    // 傳props 值必須用 propsData
    propsData: {
      text: option.text
    }
  }); // 實例化一個帶有content內(nèi)容的Notice
  // 設置 data 中的值也可以這樣直接寫
  HelloWorldInstance.isShow = option.isShow;
  HelloWorldInstance.$mount(); // 掛載但是并未插入dom,是一個完整的Vue實例
  let helloDom = HelloWorldInstance.$el;
  document.body.appendChild(helloDom); // 將dom插入body
  // 一
  // return HelloWorldInstance;
  // 二
  return () => {
    HelloWorldInstance.$el.parentNode.removeChild(HelloWorldInstance.$el);
  };
};

export default {
  install: Vue => {
    Vue.prototype.$hello = Hello;
  }
};

main.js中注入

import Hello from "@/components/global/Hello"; //這個是 index.js
Vue.use(Hello); // 使用全局組件 Hello

使用--在test.vue中

<template>
  <div>
    測試 hello 組件
  </div>
</template>
<script>
export default {
  name: "test",
  created() {
    let removeHello = this.$hello({
      content: "hello--content",
      text: "hello--text",
      isShow: "isShow-true"
    });
    setTimeout(() => {
      // 一
      // removeHello.$el.parentNode.removeChild(removeHello.$el);
      // 二
      removeHello();
    }, 3000);
  }
};
</script>

Vue.extend 自定義插件形式全局彈窗提示組件

來個升級版,寫個類似alert的組件
notice.vue

<template>
  <transition name="message-fade">
    <div :class="['message', 'notice-' + type]" v-show="visible">
      <i :class="'el-icon-' + type + ' content-' + type"></i>
      <div :class="['content', 'content-' + type]">{{ content }}</div>
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      content: "",
      type: "info", //'success','warning','error'
      duration: 2500, // 彈窗展示時長
      visible: false,
      hasClose: false,
      noticeTimer: null
    };
  },
  mounted() {
    this.close();
    if (window.noticeEl && window.noticeEl.length > 0) {
      let top = parseFloat(window.noticeEl[window.noticeEl.length - 1].style.top);
      this.$el.style.top = top + 80 + "px";
      window.noticeEl.push(this.$el);
    } else {
      window.noticeElTop = this.$el.offsetTop || document.body.clientHeight * 0.04;
      this.$el.style.top = window.noticeElTop + "px";
      window.noticeEl = [this.$el];
    }
  },
  methods: {
    close() {
      setTimeout(() => {
        this.visible = false;
        window.noticeEl = window.noticeEl.filter(val => val !== this.$el);
        let top = window.noticeElTop;
        window.noticeEl.map((val, index) => {
          val.style.top = top + index * 80 + "px";
          return val;
        });
        setTimeout(() => {
          this.$destroy(true);
          this.$el.parentNode.removeChild(this.$el);
        }, 800); // 銷毀自身組件,主要是要大于動畫執(zhí)行時間
      }, this.duration);
    }
  }
};
</script>

<style scoped lang="scss">
.message {
  position: absolute;
  top: 8vh;
  left: 50%;
  padding: 15px 20px;
  border-radius: 8px;
  background-color: #fff;
  transform: translateX(-50%);
  transition: opacity 0.2s, transform 0.2s, top 0.4s;
  font-size: 30px;
}
.content {
  display: inline-block;
  margin-left: 12px;
  min-width: 380px;
}
/* .#2ed573 */
.notice-success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
}
.el-icon-success,
.content-success {
  color: #67c23a;
}
.notice-warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
}
.notice-warning .content-warning {
  color: #e6a23c;
}
.notice-error {
  background-color: #fef0f0;
  border-color: #fde2e2;
}
.notice-error .content-error {
  color: #f56c6c;
}

// donghua
.message-fade-enter,
.message-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-8vh);
}
.message-fade-enter-to,
.message-fade-leave {
  opacity: 1;
  transform: translateX(-50%) translateY(0px);
}

.message-fade-enter-active {
  transition: all 0.4s ease;
}
.message-fade-leave-active {
  transition: all 0.4s cubic-bezier(1, 0.2, 0.8, 1);
}
</style>

跟notice.vue同級目錄的 index.js

import Vue from "vue";
const NoticeConstructor = Vue.extend(require("./notice.vue").default);

let nId = 1;
// 為了同時兼容單獨引入此組件的情況,加 export ,可以單獨導出
export const Notice = (option = { message: "提交成功!", type: "success" }) => {
  const NoticeInstance = new NoticeConstructor({
    data: {
      content: option.message,
      type: option.type
    }
  }); // 實例化一個帶有content內(nèi)容的Notice
  NoticeInstance.visible = true;
  NoticeInstance.id = "notice-" + nId++;
  NoticeInstance.$mount(); // 掛載但是并未插入dom,是一個完整的Vue實例
  NoticeInstance.$el.style.zIndex = nId + 10000;
  document.body.appendChild(NoticeInstance.$el); // 將dom插入body
  return NoticeInstance;
};
// 全局組件掛載所用,對應 Vue.use()
export default {
  install: Vue => {
    Vue.prototype.$notice = Notice;
  }
};

main.js中注入

import Notice from "@/components/global/Notice"; //這個是 index.js
Vue.use(Notice); // 使用全局組件 notice

使用--在test.vue中

<template>
  <div>
    <el-button type="danger" @click="testClick">
      Notice全局組件使用
    </el-button>
    <el-button type="danger" @click="NoticeClick">
      Notice單獨引入使用
    </el-button>
  </div>
</template>

<script>
import { Notice } from "@/components/global/Notice"; //這個是 index.js
export default {
  name: "test",
  methods: {
    NoticeClick() {
      let num = Math.floor(Math.random() * (1 - 10) + 10);
      let type = "";
      if (num <= 3) {
        type = "success";
      } else if (num <= 6) {
        type = "warning";
      } else {
        type = "error";
      }
      Notice({
        message: "提交成功!",
        type
      });
    },
    testClick() {
      let num = Math.floor(Math.random() * (1 - 10) + 10);
      let type = "";
      if (num <= 3) {
        type = "success";
      } else if (num <= 6) {
        type = "warning";
      } else {
        type = "error";
      }
      this.$notice({
        message: "提交成功!",
        type
      });
      //   this.$notify({
      //     title: "成功",
      //     message: "這是一條成功的提示消息",
      //     type
      //   });
    }
  }
};
</script>

上面引入定義的組件用了兩種方式

import helloWorld from "./index.vue";
const HelloWorldConstructor = Vue.extend(helloWorld);

等同于

const NoticeConstructor = Vue.extend(require("./notice.vue").default);
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容