自定义vue指令,通过v-name调用。这个函数接受两个参数,第一个为自定义指令的名称,第二个为一个配置项
简写:在很多时候,你可能想在 bind 和 update 时触发相同行为,而不关心其它的钩子。比如这样写
Vue.directive('name',(el, binding)=>{
el.style.backgroundColor = binding.value
console.log('bind & update hook')
});
Vue.directive('name',{
bind(el,binding){}, // 样式写这里
inserted(){}, // 行为写这里
update(){},
unbind(){},
...
});
bind
钩子函数内,el.focus()
并未生效,这是因为在 bind 钩子函数被调用时,虽然能够通过 bind
的第一个参数 el
拿到对应的 DOM 元素,但是此刻该 DOM 元素还未被插入进 DOM 树中,因此在这个时候执行 el.focus()
是无效的
- 问题:对比这里生成的 inptu 是直接在 dom 中的吗?对比在 vue bind钩子内的 el.focus() 有何区别
- 思考:document.createElement 可能掉用的时候就在 dom 中了,后边的 appendChild 只是插入在哪的问题
var box = document.querySelector('#app');
var input = document.createElement('input');
input.autofocus = 'autofocus';
box.appendChild(input)