Vue组件(component)用来构成你的App的业务模块,它的目标是App.vue。
Vue插件(plugin) 用来增强你的技术栈的功能模块, 它的目标是Vue本身。(插件是对Vue的功能的增强和补充)
vue组件
我们通常在src的目录下,新建一个component文件夹来存放公共的组件,在我们要使用组件的页面中引入组件,并且进行一个说明。组件个调用它的页面之间的通信,就是父组件和子组件的通信方式。
import Rule from '../../components/Rule.vue'
export default {
components: {
Rule,
},
data () {
return {
}
}
}
Vue插件
vue插件的编写方法的四类:
export default {
install(Vue, options) {
Vue.myGlobalMethod = function () { // 1. 添加全局方法或属性,如: vue-custom-element
// 逻辑...
}
Vue.directive('my-directive', { // 2. 添加全局资源:指令/过滤器/过渡等,如 vue-touch
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
Vue.mixin({
created: function () { // 3. 通过全局 mixin方法添加一些组件选项,如: vuex
// 逻辑...
}
...
})
Vue.prototype.$myMethod = function (options) { // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现
// 逻辑...
}
}
}
这里想具体介绍一个信息提示框的插件的编写及使用过程,其他的插件举一反三即可,无非就是逻辑更加复杂。
1.我们在src/componnets的文件夹中,建立一个 toast.vue
<template>
<div v-show="show" class="container">
<div class="mask"></div>
<div class="dialog">
<div class="head">{{head}}</div>
<div class="msg">{{msg}}</div>
<div class="btn">
<a class="btn_default" @click="cancel">取消</a>
<a class="btn_main" @click="confirm">确认</a>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
show: false,
msg: '',
head: '',
callback: ''
}
},
methods: {
cancel () {
this.show = false;
},
confirm () {
this.callback();
}
}
}
</script>
2.在src/plugins 中创建一个 toast.js
/*eslint-disable*/
import ToastComponent from '@/components/Toast.vue'
// let $vm
export default {
install (_Vue, options) {
const ToastConstructor = _Vue.extend(ToastComponent)
const instance = new ToastConstructor() //创建alert子实例
instance.$mount(document.createElement('div')) //挂载实例到我们创建的DOM上
document.body.appendChild(instance.$el)
_Vue.prototype.$showToast = (head, msg, callback) => {
instance.head = head;
instance.msg = msg;
instance.show = true;
instance.callback = callback
}
}
}
3.在main.js 中使用插件
import ToastPlugin from './plugins/toast.js'
Vue.use(ToastPlugin)
4.这样我们就可以在全局使用了。
this.$showToast ('弹窗标题', '这里显示提示的内容')
网友评论