1.2 自定义指令v-xxx绑定
1.2.1 v-xxx函数绑定
1.2.2 v-xxx格式绑定
1.2.3 例子监听元素尺寸改变
1.2.4 高级例子
<template>
<div>
<!-- 1.2.1/1.2.3 -->
<el-card v-size="cardResize">
<p>内容1</p>
<p>内容2</p>
<p>内容3</p>
<p>内容4</p>
</el-card>
<!-- 1.2.2 -->
<div>
<p v-lower-text="innerText"></p>
</div>
</div>
</template>
<script>
export default {
//局部指令,只在当前Vue中才有效
directives: {
// 1.2.1/1.2.3 使用局部注册指令的方式
resize: {
// 指令的名称
bind(el, binding) {
// el为绑定的元素,binding为绑定给指令的对象
let width = '',
height = ''
function isReize() {
const style = document.defaultView.getComputedStyle(el)
if (width !== style.width || height !== style.height) {
binding.value({ with: style.width, height: style.height }) // 关键
}
width = style.width
height = style.height
}
el.__vueSetInterval__ = setInterval(isReize, 300)
},
unbind(el) {
clearInterval(el.__vueSetInterval__)
},
},
// 1.2.2 将内容转为小写
"lower-text" : function(el, binding){
el.textContent = binding.value.toLowerCase();
}
},
data() {
return {
// 1.2.2
innerText: 'Never Give Up!(innerText)'
}
},
watch: {
},
created() {
},
mounted() {
// 1.2.1/1.2.3
cardResize(size) {
console.log(size)
},
},
methods: {
}
}
</script>
<style lang="scss" scoped>
</style>
1.2.5 全局注册
<script>
//自定义全局指令
//el:指令属性所在的html标签对象
//binding:包含指令相关信息数据的对象
Vue.directive("upper-text", function(el, binding){
console.log(el);
console.log(binding);
el.textContent = binding.value.toUpperCase();
});
</script>