Vue2.x自定义指令 & mixin & plugin
一、自定义指令
出了常见的v-for 、v-on等vue自带的指令,我们还可以去自定义指令。
比如我现在做个选项卡切换功能,希望视图和逻辑完全分离,于是定义个自定义指令,该指令可以复用,那么:
vue文件:
<template>
<div class="parent" v-nav-cur="{
curIndex,className:'nav-item',activeClass:'nav-current'
}">
<div v-for="(item,index) of items" class="nav-item" :key="index" @click="changeNav(index)">{{item}}</div>
</div>
</template>
<script>
import navCur from '../../utils/navCur'
export default {
name:'d',
directives:{
navCur
},
data(){
return {
curIndex:0,
items:['card1','card2','card3']
}
},
methods:{
//点击div的时候 触发click事件,也会触发update函数并执行里面的逻辑。
changeNav(i){
this.curIndex = i;
}
}
};
</script>
<style lang='less' scoped>
.nav-item{
width:50px;
height:25px;
border:1px solid #000;
margin:10px;
background:#ffffff;
}
.nav-current{
background: #ff0;
}
</style>
navCur.js:
export default {
// 2个方法的参数都是el,binding,vnode
//这里其实相当于我们去写原生的js,来进行封装。
//第一个方法bind会在页面渲染时候触发,第二个方法则是更新时候触发。
bind(el,binding) {
const _ops =binding.value
const _c = el.getElementsByClassName(_ops.className)
_c[_ops.curIndex].className += ` ${_ops.activeClass}`
},
update(el,binding) {
const _ops =binding.value
const _oOps = binding.oldValue//上一次的值
const _c = el.getElementsByClassName(_ops.className)
// console.log(_c,_oOps)
_c[_oOps.curIndex].className = `${_oOps.className}`
_c[_ops.curIndex].className += ` ${_ops.activeClass}`
}
}
二、mixins混入
他的作用,是让我们去复用一定的逻辑代码。
比如:新建一个show.js
// 定义一个mixin
export const showMixin = {
data() {
return {
show: true
}
},
methods: {
toggleShow() {
this.show = !this.show
}
}
}
然后在其他vue文件中引入
html部分:
<h1 v-show="show">我时隐时现</h1>
<button @click="toggleShow">切换</button>
js部分:
<script>
import { showMixin } from "../../utils/show";
export default {
mixins: [showMixin]
};
</script>
可以直接在页面中使用mixin混入的data以及methods,而且我们看到created阶段也执行并打印。
如果data或者methods里面与mixin中有命名冲突,那么组件的data和methods会覆盖并生效。
当然,在main.js入口文件中,我们也可以定义全局mixin。
Vue.mixin({
created(){
const myOption = this.$options.myOption;
if(myOption){
console.log(myOption)
}
}
})
new Vue({
render: h => h(App),
myOption:'这里是全局mixin'
}).$mount('#app')
三、plugin插件
插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:
添加全局方法或者 property。如:vue-custom-element
添加全局资源:指令/过滤器/过渡等。如 vue-touch
通过全局混入来添加一些组件选项。如 vue-router
添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
(上面是官方文档说的)
在main.js中
import MyPlugin from '../utils/plugins'
Vue.use(MyPlugin)
plugins.js:
let MyPlugin = {}
MyPlugin.install = function(Vue){
Vue.myGlobalMethod = function(){
console.log('这是插件中定义的全局方法')
}
Vue.directive('plugin-dirc',{
bind(el){
console.log('el:',el)
}
})
Vue.mixin({
created(){
console.log('plugin-mixin')
}
})
Vue.prototype.$myMethod = function(){
console.log('实例方法')
}
}
export default MyPlugin
这个还是比较容易理解的。开发过程中可以帮你整理公共部分,放入其中,有需要直接调用。