1
doommm 2020-05-24 12:35:42 +08:00
下面这么写似乎是可以的,不知道有没有更好的办法
``` <template> <div> <div v-copy="text"> {{ text }} </div> <input type="text" v-model="text" /> </div> </template> <script> export default { name: 'LabelSmall', directives: { copy: { bind(el, binding) { const copy = {}; Reflect.defineProperty(el, '__copy__', { value: copy }); copy.value = binding.value; const fn = () => { console.log('val', copy.value); }; copy.cb = fn; el.addEventListener('click', fn); }, componentUpdated(el, binding) { const copy = Reflect.get(el, '__copy__'); copy.value = binding.value; }, unbind(el, binding) { const copy = Reflect.get(el, '__copy__'); el.removeEventListener('click', copy.cb); Reflect.deleteProperty(el, '__copy__'); }, }, }, data() { return { text: 'small', }; }, }; </script> ``` |
2
faceRollingKB OP @doommm 也就是说可以使用 el 来实现 directive 实例的上下文概念,把所有上下文内容绑定到 el 的 property 上,我先试试看
|
3
faceRollingKB OP @doommm 可行的
export default function(Vue) { const key = 'copy' const property = '__v_'+key+'__' Vue.directive(key, { bind (el, binding) { el[property]={ value:binding.value, listener:function(){ copyToClipboard(this.value) } } el[property].listener = el[property].listener.bind(el[property]) el.addEventListener('click',el[property].listener) }, unbind (el) { el.removeEventListener('click',el[property].listener) }, update(el, binding){ el[property].value = binding.value } }) } |