Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a variable declared in composition be used for dynamic rendering?

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 class="mt-20 flex flex-row justify-between space-x-8">
        <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.

like image 839
Mena Avatar asked Oct 18 '25 06:10

Mena


1 Answers

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.

like image 146
str1ve Avatar answered Oct 19 '25 21:10

str1ve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!