欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用vue組件封裝共用的組件

 更新時(shí)間:2022年05月27日 11:49:10   作者:養(yǎng)只貓  
這篇文章主要介紹了使用vue組件封裝共用的組件,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

這里提供兩種vue封裝共用組件的方法

方法一

main.js中

import ListItem from './components/list.vue'//封裝共用組件方法一
Vue.component('ListItem',ListItem)

方法二

新建vue文件的時(shí)候再建個(gè)相應(yīng)的js文件。

component.js

import child from './component.vue'
 
export default child.install = function (Vue) {
  Vue.component(child.name,child)
}

main.js中

import child from './components/component/component.js'//封裝共用組件方法二
Vue.use(child)

通過(guò)上面的兩種方法定義公共組件后都可以直接<child>和<component>這樣調(diào)用組件了,無(wú)需在每個(gè)vue文件中important組件了。

說(shuō)說(shuō)方法二吧根據(jù)官方文檔提供的api

vue使用install定義安裝全局組件需要install和use這兩個(gè)api來(lái)配合才能完成。我更喜歡第一種但是今天看了公司的代碼認(rèn)識(shí)到了第二種方法,也發(fā)現(xiàn)了vue提供了不少提高生產(chǎn)效率的api往后會(huì)繼續(xù)深入去學(xué)習(xí)這些api。

同時(shí)也解決了一個(gè)困惑很長(zhǎng)時(shí)間的問(wèn)題,element ui中的message這個(gè)組件不需要vue.use安裝直接就能用,因?yàn)閑lement源碼中直接將這個(gè)組件賦值到vue的prototype上了,其他的組件都只export 暴露出install方法所以其他組件需要vue.use安裝

vue封裝公共組件調(diào)用方法

需求:項(xiàng)目中所有的提示信息都是彈框樣式的,并且顯示兩秒后自動(dòng)消失

vue頁(yè)面

<template>
? <!-- 公用提示信息頁(yè)面 -->
? <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頁(yè)面

// 公共提示信息js
import Vue from "vue";
import Toast from "./dialogMessage.vue"; //引入組件
// 返回一個(gè)“擴(kuò)展實(shí)例構(gòu)造器”
let ToastConstructor = Vue.extend(Toast);
let myToast = (text, duration) => {
  let toastDom = new ToastConstructor({
    el: document.createElement("div") //將toast組件掛載到新創(chuàng)建的div上
  });
  document.body.appendChild(toastDom.$el); //把toast組件的dom添加到body里
  toastDom.text = text;
  toastDom.duration = duration;
  // 在指定 duration 之后讓 toast消失
  setTimeout(() => {
    toastDom.dialogVisible = false;
  }, toastDom.duration);
  // 調(diào)用時(shí)  this.$toast("新內(nèi)容", 1000);
};
export default myToast;

在main.js中全局注冊(cè)

import toast from "./components/dialogMessage.js"; //引入toast函數(shù)
  //給Vue對(duì)象添加$toast方法
  Vue.prototype.$toast = toast;

頁(yè)面中使用,像使用message一樣

 this.$toast("新內(nèi)容", 1000);

效果

在這里插入圖片描述

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論