vue 自定义全局组件和通信

213 阅读1分钟

用了几天vue,在写vue时,我们都会自定义组件,比如loadingalert,每个页面都要import这个组件注入到component中去,然后再调用,感觉挺麻烦的,所以就想定义个全局的组件。

比如我们的目录机构是这样的

-- components
	-- index.js
    -- loading.vue
-- pages
-- app.vue
-- main.js

index.js

import Loading from './loading';

export default {
    install(Vue) {
        Vue.component('Loading', Loading);
    }
};

main.js

import Vue from 'vue';
import Overall from './components';

Vue.use(Overall);

【注】这样我们就注入了一个全局的loading的插件。但是这里有奇怪的现象,要注意避免。 比如我们的目录结构是这样的:

-- components
	-- loading
        -- index.js
        -- loading.vue
-- pages
-- app.vue
-- main.js

我们在main.js中引入路径为'./components/loading'时,它不是去找loading文件夹下的index.js,而是去找components文件夹下的loading.vue,当我们路劲为'./components/loading/'时,就可以找到loading文件夹下的index.js


这样我们可以直接页面入口的app.vue中直接调用了

<template>
	<div>

    	···

        	<Loading v-if="isLoading"></Loading>

        ···

    </div>
</template>

loading的显示隐藏全在app.vue里面,那我们如何在里面的子页面进行操作了,这里我们就需要用到通信$emit, $on, $off。vue的每个组件都会有个自己的this,这个this我们可以打印出来看看(图上有点错误,$root对应的根组件不是app.vue)。

vue-con.png

我们需要在app.vue中加一个监听事件

export default {
	created() {
    	this.$root.$on('showLoading', () => {
                this.isLoading = true;
            });

        this.$root.$on('hideLoading', () => {
            this.isLoading = false;
        });
    }
}

那我们在其他组件中就可以这样调用了

this.$root.$emit('showLoading');

【注】这里有个问题就是每次进入页面都会执行注册监听事件,这样代码就会重复几遍,一开始想要找vue的生命周期的钩子,想要只有在第一次初始化加载时执行脚本,后面就不会再执行,但是没找到好的方法,于是只能用off了,在每次off了,在每次on之前销毁之前对应的事件。

下面就贴一个alert的例子: alert.vue

<template>
    <div class="js_dialog" v-if="alert.visible">
        <div class="weui-mask"></div>
        <div class="weui-dialog dialog-fade-enter-active">
            <div class="weui-dialog__hd"><strong class="weui-dialog__title">{{ alert.title }}</strong></div>
            <div class="weui-dialog__bd">{{ alert.message }}</div>
            <div class="weui-dialog__ft">
                <div class="weui-dialog__btn weui-dialog__btn_primary" @click="alertSure">确认</div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    methods: {
        alertSure() {
            this.alert.visible = false;
            this.$emit('alertSure');
        }
    },

    props: ['alert']
};
</script>

<style scoped>
    @import './dialog.css';
</style>

dialog.css

.dialog-fade-enter-active {
    animation: dialog-fade-in .8s
}

@keyframes dialog-fade-in {
    0% {
        transform: translate(-50%, -90%);
        opacity: 0
    }

    to {
        transform: translate(-50%, -70%);
        opacity: 1
    }
}

.weui-mask {
    position: fixed;
    z-index: 1000;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
}

.weui-dialog {
    position: fixed;
    z-index: 5000;
    width: 80%;
    max-width: 300px;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -70%);
    transform: translate(-50%, -70%);
    background-color: #FFFFFF;
    text-align: center;
    border-radius: 3px;
    overflow: hidden;
}

@media screen and (min-width: 1024px) {
    .weui-dialog {
        width: 35%;
    }
}

.weui-dialog__hd {
    padding: 1.3em 1.6em 0.5em;
}

.weui-dialog__title {
    font-weight: 400;
    font-size: 18px;
}

.weui-dialog__bd {
    padding: .6em 1.6em 0.8em;
    min-height: 40px;
    font-size: 15px;
    line-height: 1.3;
    word-wrap: break-word;
    word-break: break-all;
    color: #999999;
}

.weui-dialog__ft {
    position: relative;
    line-height: 48px;
    font-size: 18px;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
}

.weui-dialog__btn {
    display: block;
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    text-decoration: none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    position: relative;
}

.weui-dialog__btn_default {
    color: #353535;
}

.weui-dialog__btn_primary {
    color: #14a7db;
}

.weui-dialog__btn:after {
    content: " ";
    position: absolute;
    left: 0;
    top: 0;
    width: 1px;
    bottom: 0;
    border-left: 1px solid #D5D5D6;
    color: #D5D5D6;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    -webkit-transform: scaleX(0.5);
    transform: scaleX(0.5);
}

.weui-dialog__ft:after {
    content: " ";
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    height: 1px;
    border-top: 1px solid #D5D5D6;
    color: #D5D5D6;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
}

index.js

import Alert from './alert';

export default {
    install(Vue) {
        Vue.component('Alert', Alert);
    }
};

app.vue

<template>
    <div id="app">
        <router-view></router-view>

        <Alert :alert="alert" @alertSure="alertSure"></Alert>
    </div>
</template>

<script>
    export default {
        name: 'app',
        data() {
            return {
                alert: {
                    title: '提示',
                    message: '',
                    visible: false
                }
            };
        },
        created() {
            this.$root.$on('showAlert', (message) => {
                this.alert.message = message;
                this.alert.visible = true;
            });
        },
        methods: {
            alertSure() {
                this.$root.$emit('alertSure');
            }
        }
    };
</script>

<style>
    body {
        margin: 0;
    }

    #app {
        font-family: '-apple-system-font,Helvetica Neue,sans-serif';
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #2c3e50;
    }
</style>

main.js同上

some.vue

<template>
	···
</template>
<script>
export default {
	mounted() {
    	this.$root.$off("alertSure");
        this.$root.$on("alertSure", () => {
			this.alertSure();
        });
    },
	methods: {
    	submit() {
        	this.$root.$emit('showAlert', '请将信息填写完整');
        },

        alertSure() {
        	console.log("some action");
        }
    }
}
</script>