What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this:

setup() {
    const showInvoiceItemForm = true;

    return { showInvoiceItemForm };
  },

Now, I want to show a form when a button is clicked and a function is called:

<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>

The method to handle showing the form is as follows:

addInvoiceItem() {
    this.showInvoiceItemForm = true;
    console.log(this.showInvoiceItemForm);
},

Despite setting the value of showInvoiceItemForm to true, the form isn't displayed. It seems that the value doesn't change properly. Can someone provide guidance on how to correctly use the composition API variable?

Answer №1

If my interpretation is correct, (display the form upon button click), then this solution should assist you.

<template>
  <form @submit.prevent>
    <form v-if="showInvoiceItemForm">
      <input type="text" placeholder="Enter 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>

Furthermore, if you are uncertain about the "value change", consider installing vue.js devtools as they can be quite beneficial.

Answer №2

If you want to make your variable reactive, consider using ref or reactive and transferring everything to the 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 class="mt-20 flex flex-row justify-between space-x-8">
      <button type="button" @click="addInvoiceItem"
        >Add Item</button>
      <button>Generate Invoice</button>
    </div>
  </form>
</div>

Answer №3

Discover Vue 3 Composition API

setup() function doesn't have direct access to the component instance - within setup(), this is undefined. You can access values exposed by the Composition API from the Options API, but not vice versa.

No need for using this. Try changing

v-if="this.showInvoiceItemForm"
to
v-if="showInvoiceItemForm"
and make the same adjustment when setting it.

Check out this code snippet to see if it provides any help.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the steps to execute a continuous loop of animations on a singular component using framer-motion

I'm currently working on a website that incorporates framer-motion for animations One key component of the site is an image displayed as follows: <motion.img ref={scope} initial={{ x: -200 }} alt="pa ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Learn the method to duplicate Outer HTML with the use of jQuery or Pure JavaScript

I have successfully copied the value of an input into the clipboard using the first part of the solution provided. However, I am now trying to figure out how to copy HTML content like an entire <p> tag. Currently, when attempting this, I am encounter ...

JS Nav Dots are not activating the Active Class

I have been utilizing a code snippet from this source to incorporate a vertical dot navigation feature into a single-page website. The navigation smoothly scrolls to different sections when a link is clicked, with an active highlight on the current section ...

Position the division at the location of the cursor for particular usemap components

Looking for a way to position a division on top of an image using a usemap. Interested in having the div only appear when the mouse hovers over a particular area, and at the precise location of the cursor. Came across some examples using jQuery, similar ...

Creating a GIF file using Node.js leads to a corrupted image

I have been experimenting with creating a simple GIF. I followed the example provided in this NPM library for guidance. Despite my efforts, every time I generate the GIF, it appears as a corrupted image file. CODE const CanvasGifEncoder = require('ca ...

Accessing data from localhost using Vue.js and Axios is restricted due to CORS policy and the error "Access to XMLHttpRequest" may be

Having a minor issue... Trying to retrieve a basic json file from my server for testing purposes (not an actual API). Utilizing VueJS and axios. Here is my code : getServicesAPI() { axios.get("http://51.91..../dist/API/Services.json").the ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Exploring Recursive Functions in Vue.js 3 Single File Components

How can Vue3 be used to implement recursive components effectively? When attempting to utilize recursive components in Vue 3, an error such as Cannot access before initialization may occur. Tree.vue: <template> <Tree v-if="hasChildren&quo ...

Identifying patterns within a string using JavaScript and TypeScript

Given a user-input pattern, for example [h][a-z][gho], and a string "gkfhxhk", I am attempting to determine if the string contains the specified pattern. The pattern dictates that the first character must be 'h', followed by any letter from a-z, ...

ExpressJS, defining routes, locating controllers, and documenting APIs

Utilizing expressJS 4.X and nodeJS 6.x In the past, I was defining my routes in this manner : /** * @api {get} /users/:userId Get a user * @apiName GetUser * @apiGroup User * * @apiParam {Integer} userId Users unique ID. * * @apiSuccess (Success 2 ...

Getting a Node Express 404 error while attempting to display an image that was uploaded using multer

I am facing an issue with uploading images using multer. Previously, everything was working perfectly fine on localhost. The images were getting uploaded and I could view them using the provided URL link in the code. However, after uploading it to a server ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

I'm having trouble displaying the content of my list items within the div

In my code, I have a class called "ignicoes" that includes a list as one of its attributes. This list contains other attributes such as dispositivo, latitude, longitude, and more. My goal is to retrieve the contents of this list and display them within my ...

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

Different ways to streamline the validation process for multiple input fields in a form using Vue 3

Within my application, there lies a form consisting of numerous input fields. These text input fields are displayed based on the selection made via radio buttons. I am currently validating these input fields by specifying the field name and its correspondi ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

Securing Vue.js Routing with API and JWT Tokens: My Approach

I am currently working on developing an application using Adonis.js for the API and Vue.js for the front-end. To ensure security for all API routes, I have implemented JWT token authentication. I recognize the significance of utilizing JWT to safeguard AP ...

javascript, contrasting functions and variables

As I delve into the world of Javascript and JQuery (hence why I chose the example below), I have observed an interesting behavior. I noticed that not only can I define a function and call it, but I can also just do something else mysterious by using the do ...