Event on element not firing with custom directive but firing on element that doesn't have the directive in Vue 3 #7368
Replies: 2 comments 2 replies
-
You can use like this: https://codesandbox.io/s/purple-snowflake-6gbp84?file=/src/main.js const sampledir = {
beforeMount(el, binding) {
el.value = binding.value;
el.addEventListener("input", (val) => {
// console.log(val.target.value);
binding.instance[binding.arg] = val.target.value;
});
},
/* if you want trigger this lifecycle in directive */
// in the v-sampledir:message="message /* the `message` must be modified *//"
beforeUpdate(el, binding) {
// alert("before updated");
console.log("before updated");
},
/* if you want trigger this lifecycle in directive */
// in the v-sampledir:message="message /* the `message` must be modified *//"
updated(el, binding) {
// alert("updated");
console.log("updated");
}
// when destroy suggest removeEventListener
// ...
}; This is not the best way to implement it, just an example. It is recommended to use v-model for the most complete implementation. App.vue <template>
<h1>{{ message }}</h1>
<input v-sampledir:message="message" type="text" />
<!-- <input v-model="othermsg" type="text" /> -->
</template>
<script>
export default {
data() {
return {
message: "Hello World!",
othermsg: "hey",
};
},
};
</script>
<style>
</style> main.js import { createApp } from "vue";
import App from "./App.vue";
// createApp(App).mount("#app");
const sampledir = {
beforeMount(el, binding) {
el.value = binding.value;
el.addEventListener("input", (val) => {
// console.log(val.target.value);
binding.instance[binding.arg] = val.target.value;
});
},
/* if you want trigger this lifecycle in directive */
// in the v-sampledir:message="message /* the `message` must be modified *//"
beforeUpdate(el, binding) {
// alert("before updated");
console.log("before updated");
},
updated(el, binding) {
// alert("updated");
console.log("updated");
}
// when destroy suggest removeEventListener
// ...
};
const app = createApp(App);
app.directive("sampledir", sampledir);
app.mount("#app"); |
Beta Was this translation helpful? Give feedback.
-
You seem to think that custom directive are a bit like declaring a few event listeners on an element, or something. That's not the case. I'm not quite sure what you expect to happen in your non-working example. For example: When do you expect the Custom Directives are not about events. For events, you have a special directive already:
|
Beta Was this translation helpful? Give feedback.
-
For some reason my custom directive doesn't fire on any events except beforeMount. But they do fire on elements that don't even have the custom directive. What am I doing wrong?
https://stackoverflow.com/questions/74830216/event-on-element-not-firing-with-custom-directive-but-firing-on-element-that-doe
Beta Was this translation helpful? Give feedback.
All reactions