Vue.extend
作用
创建vue实例构造函数,可通过new 创建实例 以及 mount('#id')挂载到对应元素上,可通过mount().$el获取到文档外构建好的实例根元素
使用
import MyAlert from './myalert.vue'
const props = { message: 'test' }
// 生成创建vue实例的构造函数
const Alertmsg = Vue.extend(MyAlert)
// new vue实例,props的属性值必须为propsData (参考:https://cn.vuejs.org/v2/api/#propsData)
new Alertmsg({ propsData: props }).$mount('#my-containt') // 将MyAlert挂载在id = "my-containt"节点上
// $mount(#id | .class | element | ): 挂载在某个文档节点下
// 值为空时则在文档外创建vue实例:可以通过$mount().$el获取vue实例的根元素
复制代码
Vue.use
作用
vue.use使用vue插件的入口,主要为当前项目的vue全局注入方法、全局变量等,以待项目后续使用
使用
vue.use(object | function)
object时vue.use会调用 object.install()
function时vue.use会调用 function()
插件书写
写一个简单的toast,实现在项目中import toast from 'mytoast' vue.use(toast)
然后在项目中可通过this.$toast调用
mkdir mytoast
npm init
复制代码
先写toast组件 mytoast/toast.js
<template>
<transition>
<div class='parent' v-if='show'>
<div class='child'>{{message}}</div>
</div>
</transition>
</template>
<script>
export default {
name: 'toast',
data () {
return {
message: 'nessage',
show: false
}
}
}
</script>
复制代码
再写一个插件出口 mytoast/index.js,结合前面vue.use的原理:应该export default object/funxtion
插件出口为对象
import toastComponent from './toast.vue'
const Toast = {} // 需要导出的对象
let $vm // 存储Vue实例
Toast.install = function (Vue, options) {
// 实现this.$toast,需要在vue全局挂载$toast 此处使用挂载到prototype上
// message toast内容 duration toast展示时长 callback toast消失后执行的回调
Vue.prototype.$toast = function (message, duration, callback) {
// 获取构造函数
let Ext = Vue.extend(toastComponent)
if (!$vm) {
// 构造一个vue实例
$vm = new Ext()
}
// 给插件出口对象赋值
$vm.message = message || 'message'
$vm.duration = duration || 2500
$vm.show = true
// 挂载到dom中
document.body.appendChild($vm.$mount().$el) // 挂载元素
// 展示时长
const timer = setTimeout(() => {
$vm.show = false
clearTimeout(timer)
typeof callback === 'function' && callback()
}, $vm.duration)
}
export default Toast
复制代码
插件对象为函数
import toastComponent from './toast.vue'
let vm // 存储Vue实例
// 需要导出的函数
const Toast = function (Vue, options) {
// 实现this.$toast,需要在vue全局挂载$toast 此处使用挂载到prototype上
// message toast内容 duration toast展示时长 callback toast消失后执行的回调
Vue.prototype.$toast = function (message, duration, callback) {
// 扩展构造对象
let Ext = Vue.extend(toastComponent)
if (!$vm) {
// 实例化一个对象
$vm = new Ext({
el: document.createElement('div') // 组件根元素
})
}
// 给插件出口对象赋值
$vm.message = message || 'message'
$vm.duration = duration || 2500
$vm.show = true
// 挂载到dom中
document.body.appendChild($vm.$el) // 挂载元素
// 展示时长
const timer = setTimeout(() => {
$vm.show = false
clearTimeout(timer)
typeof callback === 'function' && callback()
}, $vm.duration)
}
export default Toast
复制代码