Creating Conditional Vue Components

I am looking to dynamically create a list of actions, each of which is a component, based on a condition where the object variable store.plan is not empty. I attempted using v-if, which worked well for rendering but not for creating the component.

However, I encountered an error:

Uncaught (in promise) TypeError: action is undefined

You can find the complete code of this component here.

Could you please guide me on how to solve this issue? Thank you in advance.

<template>
    <div class="planlist" v-if="parse">
        <ul id="planOl">
        <Action
        v-for="action in store.plan"
            :action_id="action.act_id"
            :actor="action.actor"
            :color="action.color"
            :size="action.size"
            :lego_name="action.lego"
            :pick_pos="action.pick"
            :place_pos="action.place"
            :blocked="action.blocked"
            :status="action.status"
            :key="action.act_id"
        />
        </ul>
    </div>
</template>

<script>
import Action from '../components/Action.vue';
import { store } from '../js/store.js'

export default {
    name: 'Plan', 
    data() {
        return {           
            store,
        }
    },
    computed: {
        parse() { 
            if (store.plan.length > 0) { 
                return true;
            }
            return false;
        }
    },
    components: {Action}
}
</script>

Answer №1

Have you considered using the concept of optional chaining in your JavaScript code:

parse() { 
  return store?.plan?.length > 0 ? true : false
}

Also, ensure you are not mixing v-if and v-for directives. It's recommended to wrap your component with a div containing v-if condition:

<ul id="planOl">
  <div v-if="parse">
    <Action
    v-for="action in store.plan"
        :action_id="action.act_id"
        :actor="action.actor"
        :color="action.color"
        :size="action.size"
        :lego_name="action.lego"
        :pick_pos="action.pick"
        :place_pos="action.place"
        :blocked="action.blocked"
        :status="action.status"
        :key="action.act_id"
    />
  </div>
</ul>

Answer №2

It is not advisable to combine the v-if and v-for directives on the same element as it can lead to syntax confusion.

Looking at your code, the computed property parse is being used to check the length of an array. Consider moving the v-if directive to a wrapping container element like an ul.

Example in the template :

<ul id="planOl" v-if="parse">
 <Action v-for="action in store.plan">...</Action>
</ul>

Corresponding script :

computed: {
    parse() { 
        return store.plan.length > 0 ? true : false;
    }
}

Answer №3

  1. In order to simplify the process, consider moving the store.plan to a computed property for easier use within the template and parse property.
  2. Instead of returning true and false based on conditions, simply return store.plan.length from the computed property to achieve the same result.
  3. If you need to use v-if just outside the Action component, utilize the template tag to achieve this without adding unnecessary elements.

Implementing the following changes can assist in resolving the issues:

<template>
    <div class="planlist">
        <ul id="planOl">
            <template v-if="parse">
                <Action
                    v-for="action in plan"
                    :key="action.act_id"
                    :action_id="action.act_id"
                    :actor="action.actor"
                    :color="action.color"
                    :size="action.size"
                    :lego_name="action.lego"
                    :pick_pos="action.pick"
                    :place_pos="action.place"
                    :blocked="action.blocked"
                    :status="action.status"
                />
            </template>
        </ul>
    </div>
</template>

<script>
import Action from "../components/Action.vue";
import { store } from "../js/store.js";

export default {
    name: "Plan",

    components: {
        Action,
    },

    computed: {
        // A computed property to access the plan ()
        plan() {
            return store.plan;
        },

        parse() {
            /**
             * 1. The plan should not be null, empty, or undefined
             * 2. The plan should be an array to apply the length property
             * 3. If it's an array, it should contain data (have a length)
             */
            return this.plan && Array.isArray(this.plan) && this.plan.length;
        },
    },
};
</script>

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

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

Encountering a problem with NodeJS and ExpressJS Router.use()

Encountering an Error: // Necessary module imports // Setting up view engine app.use(favicon(path.join(__dirname, 'public/images', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.ur ...

Discovering whether an image contains a caption with the help of JavaScript

There are various websites that display captions on images in paragraphs, h1 tags, or contained within a div along with the image. I am interested in learning how to determine if an image has an associated caption using JavaScript, especially when the cap ...

What steps are involved in extracting post data from the javascript DOM using php?

Having an issue where my JavaScript sends data to PHP, but the parsing in PHP keeps failing. The data is received by PHP and displayed in a text area, however, it needs proper formatting before being parsed. Can anyone advise on how to correctly format the ...

Loop through and display content on the webpage with a for loop

I'm attempting to create a loop that will display information in three different areas of the DOM. Essentially, I have an array of enemies and I want to randomly select three of them to display in separate HTML div classes (firstEnemy, secondEnemy, th ...

How can we display a different navbar based on whether the user is logged in or not?

Can anyone share the most effective methods for displaying a different navbar based on whether or not a user is logged in? I have considered a few approaches: One option might involve creating two separate navbars in the HTML file and using CSS to tog ...

Stack two divs together

It may seem silly, but I just can't get it to work. I'm attempting to enclose two divs with different classes in another div, but my current code is automatically closing the divs. There are multiple sets of divs with classes .panel-heading and ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

Manage the angularJS user interface switch through an external event

I have implemented an AngularJS Material UI switch and I am looking to update its status based on an external event. This event occurs when a MQTT message is received on a specific topic that is published. To achieve this, I am utilizing a Node.js MQTT cli ...

Utilize data retrieved from an API to customize the appearance of buttons through the combination of React and Sass styling techniques

I retrieved data from an API and used it to create a list of buttons. The data I received includes names and color codes. { name: "bob", colorCode: "#DC7472" }, { name: "ben", colorCode: "#69DCD1" }, { name: &q ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

Can the parent document interact with Shadow DOM elements?

When it comes to user-created shadow DOM elements, this question focuses more on accessibility using the date input type: For instance, let's say there is a date input on a webpage. After some editing, the shadow DOM markup for this element (in Chrom ...

Whenever I attempt to implement NavigationContainer in react native, an error always pops up

Hey there! I'm currently diving into the world of React Native and decided to start with a small project. However, I've encountered a persistent error when trying to use the NavigationContainer. Here's the error message I keep getting: error ...

Add and condense sub-row

I am struggling to make the child row collapse and append when clicking on the parent row. It seems like my code is not working properly. Can anyone offer some guidance or assistance? This is the code for the parent row: $j(document).ready(function(){ $ ...

Error message: "When namedPlaceHolder parameter is disabled, bind parameters must be in the form of an

Currently revamping my query due to a crucial API redesign. With the presence of a "file" as multipart/form-data, I found the need for a form handler since NextJS lacked one. After some workarounds with "multiparty", now I can successfully parse the incomi ...

Activate function upon closure of window.open

I'm facing an issue where I need to load a URL in window.open that saves some cookies in my browser. After the window.open is closed, I want to access those cookies but I haven't been able to find a way to do it. I've tried the following cod ...

Utilizing ng-repeat in a tabset to create an interactive and customizable tab interface

I am using angular ui tab (angular-ui.github.io/bootstrap/) and I expected that with ng-repeat, I would be able to make it dynamic, meaning the user can add tabs. However, unexpectedly it duplicates the tabs. Here is a demo: http://plnkr.co/edit/iHi1aOfbz ...

Generate some text on the following page utilizing the JavaScript function window.print()

Within my ASP.NET MVC View, I included this code snippet to display the content of my webpage: var newWindow = window.open(); newWindow.document.write(); newWindow.document.write(document.getElementById("sbmtform").innerHTML); newWindow.print(); I also ...