Vue插件编写
栏目: JavaScript · 发布时间: 6年前
内容简介:有时候要写一个弹窗或者 Toast 组件,用的时候总不可能要打它引入到 template 中,这时候就需要 Vue 的自定义插件了这里以一个 toast 插件为例
有时候要写一个弹窗或者 Toast 组件,用的时候总不可能要打它引入到 template 中,这时候就需要 Vue 的自定义插件了
-
添加全局方法或者属性,如: vue-custom-element
-
添加全局资源:指令/过滤器/过渡等,如 vue-touch
-
通过全局 mixin 方法添加一些组件选项,如: vue-router
-
添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
-
一个库,提供自己的 API,同时提供上面提到的一个或多个功能,如 vue-router
Toast 插件编写
这里以一个 toast 插件为例
<template>
<transition name="slideup">
<div v-show="active">
<span></span>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
active: false,
text: " "
};
},
methods: {
show(text) {
if (text) {
this.text = text;
}
this.active = true;
setTimeout(() => this.hide(), 2000);
},
hide() {
this.active = false;
// 结束动画时间, 记得销毁
setTimeout(() => this.$destroy(), 350);
}
},
destroyed() {
// 销毁时候移除DOM
document.body.removeChild(this.$el);
},
install(Vue) {
// 创建组件
const VueToast = Vue.extend(this);
// 导出方法到Vue.prototype
Vue.prototype.$toast = params => {
// 创建实例
var toast = new VueToast();
// 渲染生成html,toast.$el
toast.$mount();
// html放到dom上
document.body.appendChild(toast.$el);
toast.show(params);
};
}
};
</script>
可以看出比一般的组件多了 install 方法和执行生命周期的一些方法,因此需要熟悉组件和 Vue 生命周期
核心方法是 install,把$toast 绑定在 Vue.prototype 上
Toast 插件使用
import Toast from './components/Toast.vue' Vue.use(Toast)
Vue.use 注册一次即可在任何地方使用。多注册也不用担心 Vue.use 会自动阻止多次注册相同插件,届时只会注册一次该插件
在任意组件内通过 this.$toast("提示信息"); 即可使用
另一种写法
还有一种就是把 install 方法拆分出去形成一个单独的 js 文件,代码如下。
此种的好处是不对组件干扰,也可以使用 Vue.extend 对组件进行拓展
import Toast from './components/Toast.js' Vue.use(Toast)
<template>
<transition name="slideup">
<div v-show="active">
<span></span>
</div>
</transition>
</template>
<script>
export default {
data() {
return {
active: false,
text: " "
};
},
methods: {
show(text) {
if (text) {
this.text = text;
}
this.active = true;
},
hide() {
this.active = false;
}
}
};
</script>
import Toast_Vue from './Toast.vue'
const Toast = {
install(Vue) {
// 返回构造器
let creater = Vue.extend(Toast_Vue)
function toast(param) {
let instance = new creater()
instance.$mount()
instance.text = param
document.body.appendChild(instance.$el)
instance.active = true
setTimeout(() => instance.hide(), 2000)
setTimeout(() => {
document.body.removeChild(instance.$el)
instance.$destroy()
}, 2500)
}
Vue.prototype.$toast = toast
}
}
export default Toast
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
无处安放的互联网隐私
【美】茱莉亚·霍维兹 【美】杰拉米·斯科 / 中国人民大学出版社有限公司 / 2017-7-1 / CNY 55.00
在当今互联网时代,我们的隐私权已经受到了威胁,政府或企业可以追踪我们的电话,搜索引擎可以记录我们的在线浏览记录以及恒温器的设置以及更多信息。在当代,保卫隐私权不只是简单地描述出存在的问题或者警告人们隐私权已经丧失,隐私权的护卫者们提出了解决策略。他们密切关注商业实践、公共政策和技术设计以及人物,应该继续下去吗?条件就是:有问题,让我们找到解决之道。一起来看看 《无处安放的互联网隐私》 这本书的介绍吧!