在vue中,我们使用组件的方式,一般是写一个.vue文件,然后通过import引入,通过components注册来使用使用。
还有一种方式,是我们在使用第三方ui组件的时候(比如elementui),是直接在main.js文件中,通过Vue.use()来注册。这种方式注册的组件我们就叫做全局组件。
那我们自己如何定义全局组件呢?
第一步,我们先写一个组件:
// test.vue 文件
<template>
<div>
this is test
</div>
</template>
<script>
export default {
name: 'test'
}
</script>
第二步,我们注册这个组件:
在test.vue同级目录建一个index.js文件
import test from './test.vue'
export default (Vue) => {
Vue.component(test.name, test)
}
第三步,把组件注册到全局:
在main.js文件中,加入两行代码
import test from './components/test'
Vue.use(test)
这样我们就可以在任何地方直接使用test这个组件。(是不是很简单)
在第三方ui组件中,一般还有一种特殊的组件,我们是通过api来调用的,比如element的message组件。
那么如何通过api来调用组件呢?(我们来做一个最简单的message组件)
第一步,同样的也是先写一个组件:
这个组件也很简单,一个div,里面有个span显示内容,需要的参数是content。为什么有个style的计算属性呢?
这是因为,我们在写组件的时候,一般会写一个简单一点的通用性组件,只放基本的内容,然后通过组件的继承来扩展它的功能,这样可以增加组件的灵活性。
新建一个notify.js文件
// notify.js文件
<template>
<transition name="fade">
<div class="notification"
:style="style"
>
<span class="content">{{content}}</span>
</div>
</transition>
</template>
<script>
export default {
name: 'notify',
props: {
content: {
type: String,
required: true
}
},
computed: {
style() {
return {
}
}
}
}
</script>
<style lang="stylus" scoped>
.notification
display: inline-flex
background-color #303030
color rgba(255, 255, 255, 1)
align-items center
padding 20px
min-width 280px
box-shadow 0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12)
flex-wrap wrap
transition all .3s
.content
padding 0
.btn
color #ff4081
padding-left 24px
margin-left auto
cursor pointer
.fade-enter-active, .fade-leave-active
transition opacity .5s
.fade-enter, .fade-leave-to
opacity 0
</style>
第二步:扩展基础组件
新建一个fun-notify.js文件
为了方便,这路的扩展是写死的,但是实际项目中,肯定是会有很多需要扩展的属性和方法。(比如组件自动隐藏方法,这些直接在基础组件里面写死肯定是不合理的)
import notify from './notify'
export default {
extends: notify,
computed: {
style () {
return {
position: 'fixed',
right: '20px',
bottom: `20px`
}
}
}
}
第三步:写一个挂载组件的方法
通过api来调用组件,那么我们肯定要写一个全局方法,来动态的挂载组件。
新建一个function.js文件
方法也很简单,先把用户传过来的参数,传给props,然后把组件实例通过$mount()进行挂载。
import Vue from 'vue'
import Component from './fun-notify'
const NotificationConstructor = Vue.extend(Component)
const notifyMessage = (options) => {
const instance = new NotificationConstructor({
propsData: {
...options
}
})
instance.vm = instance.$mount()
document.body.appendChild(instance.vm.$el)
}
export default notifyMessage
第四步:把方法和组件注册到全局
新建一个index.js文件
import notify from './notify.vue'
import notifyMessage from './function'
export default (Vue) => {
Vue.component(notify.name, notify),
Vue.prototype.$notifyMessage = notifyMessage
}
然后在main.js文件中加入两行代码
import notify from './components/notify'
Vue.use(notify)
第五步:调用
this.$notifyMessage({
content: 'this is test'
})

message提示组件成功显示。
从上面的message例子可以看出来,现在这个message组件是及其简陋的,而且还有很多功能没有实现。比如自动消失,多个message自动计算高度,dom自动删除等。由于篇幅原因,这里就不详细说明了。
大家有兴趣的话,可以看demo。
网友评论