自定義指令
自定義指令——第一種方法(傳參)
//自定義指令——第一種,可以註冊在全局(main.js)裏,也可以註冊局部(需要使用的vue文件)
Vue.directive('clickReport', {
inserted(el, binding, vnode) {
el.addEventListener('click', e => {
console.log('參數',binding.value);//參數 {a: 2, b: 2}
//在這裏寫你的處理邏輯
});
},
});
<!--/* eslint-disable */-->
<template>
<div class="testDirective" v-clickReport="{a:2,b:2}">
點擊
</div>
</template>
<script>
export default {
name: 'testDirective',
data () {
return {
title: '測試'
}
},
methods: {//方法
},
created(){//渲染前執行
document.title = this.title;
},
mounted(){//渲染後執行
},
computed: {},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
自定義指令——第二種方法(傳方法)
//自定義指令——第二種,可以註冊在全局(main.js)裏,也可以註冊局部(需要使用的vue文件)
Vue.directive('clickReport', {
inserted(el, binding, vnode) {
el.addEventListener('click', e => {
//在這裏寫你的處理邏輯
binding.value(); //觸發方法
});
},
});
<!--/* eslint-disable */-->
<template>
<div class="testDirective" v-clickReport="test">
點擊
</div>
</template>
<script>
export default {
name: 'testDirective',
data () {
return {
title: '測試'
}
},
methods: {//方法
test(){
console.log('被觸發了');
}
},
created(){//渲染前執行
document.title = this.title;
},
mounted(){//渲染後執行
},
computed: {},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
自定義指令——第三種方法(傳方法並傳參)
//自定義指令——第三種,可以註冊在全局(main.js)裏,也可以註冊局部(需要使用的vue文件)
let nowTime = 0;
Vue.directive('clickReport', {
inserted(el, binding, vnode) {
el.addEventListener('click', e => {
//在這裏寫你的處理邏輯
if(new Date() - nowTime > 1000) {//限制用戶一秒內多次點擊
nowTime = new Date();
let that = vnode.context;
that[binding.arg](binding.value);//回調方法
}
});
},
});
//xmlns:v-clickReport="http://www.w3.org/1999/xhtml"這一串需要加上去,不然會報錯
<!--/* eslint-disable */-->
<template xmlns:v-clickReport="http://www.w3.org/1999/xhtml">
<div class="testDirective" v-clickReport:test="{a:1,b:2}">
點擊
</div>
</template>
<script>
export default {
name: 'testDirective',
data () {
return {
title: '測試'
}
},
methods: {//方法
test(val){
console.log('被觸發了',val); //被觸發了 {a: 1, b: 2}
}
},
created(){//渲染前執行
document.title = this.title;
},
mounted(){//渲染後執行
},
computed: {},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>