I'm trying to refactor my code into couple component, so that it looks more readable and cleaner, but I got confused how to use data variable child component in parent. In the ModalIdentifier the addPI_ID
it's supposed to set into false
so that we click ADD
button the modal identifier will set into true and modal will pop up
ModalIdentifier.vue (child)
<template>
<v-dialog v-model="addPI_ID" width="600">
</v-dialog>
</template>
export default {
props: ["addPI_ID"],
}
addUser.vue(parent)
<template>
<div>
<modal-identifier :addPI_ID="false"></modal-identifier>
//there's button, if we click that modal identifier dialog will pops up
<v-btn
color="#8FC23E"
@click="addPI_ID = true"
>ADD</v-btn>
</div>
</template>
this part I got confused, what's the better idea ?
CodePudding user response:
Props are for parent -> child
You can use $emit for child -> parent
in parent:
- Use addPI_ID to control the dialog(show/hide), passing the value through props from parent to child
- Listen the event "update" to be emitted from child to parent with the new value of addPI_ID
- Changing the value of addPI_ID to true (show dialog) when the button ADD is clicked
<modal-identifier :addPI_ID="addPI_ID" v-on:update="addPI_ID = $event"></modal-identifier>
<v-btn color="#8FC23E" @click="addPI_ID = true">ADD</v-btn>
in child:
- Create a computed property "show", to emit our custom event "update" to parent(with the new value of addPI_ID), whenever we set the value of "show". And when we read the value of "show"(get) it returns the current value of our prop addPI_ID
- Prop addPI_ID receive the value from parent
<template>
<div>
<v-dialog v-model="show" width="600">
<v-btn color="primary" @click="show = false">Close</v-btn>
</v-dialog>
</div>
</template>
<script>
export default {
props: {
addPI_ID: Boolean
},
computed: {
show: {
get() {
return this.addPI_ID;
},
set(addPI_ID) {
this.$emit('update', addPI_ID);
},
},
},
};
</script>
hope it helps! ;)
CodePudding user response:
I am not sure if I understood your question correctly, but I think you shouldn't be passing "false" into modal-identifier element in the parent. You should pass in the actual value of addPI_ID, like this:
<modal-identifier :addPI_ID="addPI_ID"></modal-identifier>
You should also declare a variable addPI_ID in the parent if you haven't already:
data: {
...
addPI_ID: false,
},