大家好, Capybara 继续与大家一起学习Vue框架。坚持就是胜利。
day05
自定义指令
指令注册
directive 指令
main.js(全局注册)
// inserted 会在 指令所在的元素,被插入到页面中时触发
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// // 1. 全局注册指令
Vue.directive('focus', {
// inserted 会在 指令所在的元素,被插入到页面中时触发
inserted (el) {
// el 就是指令所绑定的元素
console.log(el);
el.focus()
}
})
new Vue({
render: h => h(App),
}).$mount('#app')
App.vue(局部注册)
directives
<template>
<div>
<h1>自定义指令</h1>
<input v-focus ref="inp" type="text">
</div>
</template>
<script>
export default {
// mounted () {
// this.$refs.inp.focus()
// }
// 2. 局部注册指令
directives: {
// 指令名:指令的配置项
focus: {
inserted (el) {
el.focus()
}
}
}
}
</script>
<style>
</style>
指令的值
实操:
(1)没有传入指令的值
(2)传入指令的值
(3)传入指令的值(并用于修改元素文字颜色)
// 2. update 指令的值修改的时候触发,提供值变化后,dom更新的逻辑
<template>
<div>
<h1 v-color="color1">指令的值1测试</h1>
<h1 v-color="color2">指令的值2测试</h1>
</div>
</template>
<script>
export default {
data () {
return {
color1: 'red',
color2: 'orange'
}
},
directives: {
color: {
// 1. inserted 提供的是元素被添加到页面中时的逻辑
inserted (el, binding) {
// console.log(el, binding.value);
// binding.value 就是指令的值
el.style.color = binding.value
},
// 2. update 指令的值修改的时候触发,提供值变化后,dom更新的逻辑
update (el, binding) {
console.log('指令的值修改了');
el.style.color = binding.value
}
}
}
}
</script>
<style>
</style>
修改指令的值:
页面发生变化
(打印多次,是内部更新机制问题)
自定义指令 - v-loading 指令封装
代码:
<template>
<div clas