I want a vue js v3 project using composition api, I have declared a variable like this
setup() {
const showInvoiceItemForm = true;
return { showInvoiceItemForm };
},
Now I want to display a form when a button is clicked and a function is called like this
<form @submit.prevent="submit">
<InvoiceItem
:form="form"
v-if="this.showInvoiceItemForm"
></InvoiceItem>
<div >
<BreezeButton type="button" @click="addInvoiceItem"
>Add Item</BreezeButton
>
<BreezeButton>Generate Invoice</BreezeButton>
</div>
</form>
And the method is like this
addInvoiceItem() {
this.showInvoiceItemForm = true;
console.log(this.showInvoiceItemForm);
},
From the console, I can see that the value of showInvoiceItemForm
is set to true
but the form is never shown. It looks like the value never really changes, so what is the proper way to use the composition api variable.
CodePudding user response:
If I understand you correctly, (it is necessary to show the form when the button is clicked), then I hope this solution will help you.
<template>
<form @submit.prevent>
<form v-if="showInvoiceItemForm">
<input type="text" placeholder="Type text here">
</form>
<div>
<button @click="addInvoiceItem">Add Item</button>
<button>Generate Invoice</button>
</div>
</form>
</template>
<script>
import { ref } from 'vue';
export default {
setup () {
let showInvoiceItemForm = ref(false);
function addInvoiceItem() {
showInvoiceItemForm.value = !showInvoiceItemForm.value;
console.log(showInvoiceItemForm.value);
};
return {showInvoiceItemForm, addInvoiceItem}
}
}
</script>
Also, if you not sure in "value change", you can install vue.js devtools, it's very useful.
CodePudding user response:
You can try to make your variable reactive with ref
or reactive
and move all to setup function:
const { ref } = Vue
const app = Vue.createApp({
el: "#demo",
setup() {
const showInvoiceItemForm = ref(false);
const addInvoiceItem = () => {
showInvoiceItemForm.value = true;
console.log(showInvoiceItemForm.value);
}
return { showInvoiceItemForm, addInvoiceItem };
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<form @submit.prevent="submit">
<input v-if="showInvoiceItemForm" />
<div >
<button type="button" @click="addInvoiceItem"
>Add Item</button>
<button>Generate Invoice</button>
</div>
</form>
</div>
CodePudding user response:
setup()
itself does not have access to the component instance -this
will have a value ofundefined
insidesetup()
. You can access Composition-API-exposed values from Options API, but not the other way around.
You do not have to use this
. See if changing v-if="this.showInvoiceItemForm"
to v-if="showInvoiceItemForm"
works, same for when you set it.
Try this code snippet and see if it helps.