Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

26 - 实现简易版v-model指令 #2750

Open
T0205 opened this issue Jul 16, 2024 · 0 comments
Open

26 - 实现简易版v-model指令 #2750

T0205 opened this issue Jul 16, 2024 · 0 comments

Comments

@T0205
Copy link

T0205 commented Jul 16, 2024

`<script setup lang='ts'>
import { ref, watchEffect } from "vue"
/**

  • Implement a custom directive
  • Create a two-way binding on a form input element
    */
    interface DirectiveBinding {
    value: string
    }

interface DirectiveEl extends HTMLInputElement {
value: string
vueInputListener: any
}

const VOhModel = {
mounted(el: DirectiveEl, binding: DirectiveBinding) {
el.value = binding.value;
console.log('执行mounted')
const handleInput = (e: Event) => {
value.value = (e.target as DirectiveEl).value
};
el.addEventListener('input', handleInput, false);
// 存储监听器引用以便稍后可以移除
el.vueInputListener = handleInput;
},
updated(el: DirectiveEl, binding: DirectiveBinding) {
console.log('执行updated')
el.value = binding.value;
},
unmounted(el: DirectiveEl) {
if (el.vueInputListener) {
el.removeEventListener('input', el.vueInputListener, false);
}
}
};

const value = ref("Hello Vue.js")
const setValue = () => {
value.value = 'tang'
}

</script>

{{ value }}

改变
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant