美文网首页
Vue.js笔记 — 自定义组件

Vue.js笔记 — 自定义组件

作者: honglingdai | 来源:发表于2018-03-08 17:38 被阅读0次

1、先创建一个vue的 loading.vue 文件

<template>
    <div class="loading-wrapper">
        <div class="aircle"></div>
    </div>
</template>
<style lang="less" scoped>
    .loading-wrapper {
        position: fixed;
        width: 100%;
        height: 100%;
        left: 0; top: 0;
        background: rgba(0, 0, 0, .5);
        .aircle {
            width: 300px;
            height: 300px;
            position: absolute;
            left:0;top:0;right:0;bottom:0;
            margin: auto;
            border-radius: 50%;
            background: linear-gradient(#000 50%, #fff 0%);
            display: flex;
            align-items: center;
            animation: rotate 2s linear infinite;
        }

        .aircle:after,
        .aircle:before {
            content: "";
            flex: 1;
            height: calc(100% / 6);
            border-radius: 50%;
            border: 50px solid #000;
            transform-origin: 0 50%;
            transform: scale(0.5);
            animation: change 1s ease-in-out infinite alternate;
        }

        .aircle:after {
            background: #000;
            border-color: #fff;
            transform-origin: 100% 50%;
            animation-delay: -1s;
        }
        .aircle:before {
            background: #fff;
        }

        @keyframes change {
            100% {
                transform: scale(1.5);
            }
        }

        @keyframes rotate {
            100% {
                transform: rotate(360deg);
            }
        }
    }
</style>

2.在创建一个JS 文件引入这个loading.vue
index.js

import Vue from 'vue'
import LoadingComponent from './loading.vue'


//extend 是构造一个组件的语法器.传入参数,返回一个组件
let LoadingConstructor = Vue.extend(LoadingComponent);
let initComponent;

//导出 显示loading组件
export const showLoading = (option={}) => {
    initComponent = new LoadingConstructor();
    initComponent.$mount();
    document.querySelector(option.container || 'body').appendChild(initComponent.$el);
}

//导出 移除loading组件
export const hideLoading = () => {
    initComponent.$el.parentNode.removeChild(initComponent.$el)
}

3.最后创建一个js文件统一挂载所有自定义组件到vue原型上(所有的自定义组件都挂在到这个js)
output.js

import Alert from './alert/index.js'  //alert组件
import { showLoading, hideLoading } from './loading/index.js' //loading组件

const install = function(Vue) { //通过install方法挂载到Vue原型上去
    Vue.prototype.$alert = Alert;
    Vue.prototype.$showLoading = showLoading;
    Vue.prototype.$hideLoading = hideLoading;
}
export default install

4.最后在main.js中引入 output.js

import globalComponents from './components/output'
Vue.use(globalComponents);

最后页面调用

created () {
    this.$showLoading()

    setTimeout( () => {
        this.$hideLoading()
    }, 2000);

}

相关文章

网友评论

      本文标题:Vue.js笔记 — 自定义组件

      本文链接:https://www.haomeiwen.com/subject/edcrfftx.html