Switch component based on v-if condition - Vue.JS

I am currently working on a parent component that includes various graphics. Depending on the specific needs, I want to pass a particular graphic (child component) dynamically to another component. However, I am unsure of how to achieve this for the user.

Here is the code for my HTML charts (chart.vue):

    <template>  
        <div >
          <bars v-if="type == 'bar'">
             <div class="row gutter-sm">
                <div class="col-md-3"> 
                   <apexchart  ref="chart1" type="bar" :options="options" :series="updatedData"></apexchart>
                </div>
             </div> 
                <div class="col-md-3"> 
                   <apexchart ref="chart3" type="bar" :options="options3" :series="updatedData"></apexchart>
                </div>
           </bars>
           <lines v-if="type == 'line'">
              <div class="row gutter-sm">
                <div class="col-md-3"> 
                   <apexchart ref="chart4" type="line" :options="options4" :series="updatedData"></apexchart>
                </div>  
             </div>
           </lines>
       </div>
    <template>

If I intend to pass on bar graphics to my menu.vue component, would it look like this?

Here is the code for my HTML menu:

    <template>  
        <div >
          <table class="data-table-2" style="min-width: 800px">
             <charts type="bar"/>
          </table>
       </div>
    <template>

Scripts for the menu:

   <script>
   
       import charts from "./charts.vue"
       
       export default {
         name: 'menu',
         components: {
            charts
         }
       }
    </script>

Answer №1

The method of passing values from the parent component to the child component needs adjustment

<template>  
    <div >
      <table class="data-table-2" style="min-width: 800px">
         <charts :type='bar'/>
         <charts :type='line'/>
         <charts />
      </table>
   </div>
<template>

The child component receives a value, and you have the option to set a default value:

// Initialize in the child component
props: {
  type: {
    type: String,
    default: 'bar' // Set a default value
  }
},
data(){
 ...
}

Then you can utilize the type in the child component

<template>  
    <div >
      <bars v-if"type == 'bar'">
         <div class="row gutter-sm">
            <div class="col-md-3"> 
               <apexchart  ref="chart1" type="bar" :options="options" :series="updatedData"></apexchart>
            </div>
         </div> 
            <div class="col-md-3"> 
               <apexchart ref="chart3" type="bar" :options="options3" :series="updatedData"></apexchart>
            </div>
       </bars>
       <lines v-if"type == 'line'">
          <div class="row gutter-sm">
            <div class="col-md-3"> 
               <apexchart ref="chart4" type="line" :options="options4" :series="updatedData"></apexchart>
            </div>  
         </div>
       </lines>
   </div>
<template>

Answer №2

You must ensure that a Props is defined in the child component.

//Child Component Script
export default ChildComponent {
    data() {
        return {}
    },
    props: {
        type: string,
    }
}

Within the parent component, you should include the child component and provide the type of data like so: //parent component

<template>
    <div>
        <child-component :type="line"/>
    </div>
</template>

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

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Tips for working with elements in WebDriver that are created dynamically by JavaScript

As a novice in automation using Java and WebDriver, I find myself facing a particular issue: Browse for a specific customer Select a new customer type from a dropdown menu Click on the Save button Outcome: Upon trying to change the customer, a message p ...

Reply in Loopback on remote method beforeRemote hook is to be sent

In my application, I am utilizing loopback v3. The specific use case I am tackling involves validating the presence of a token in the request header. If the token is invalid, I need to send an appropriate message in a standardized format. My approach has b ...

Error message in React-router: Cannot read property 'func' of undefined, resulting in an Uncaught TypeError

When attempting to launch my react application, I encountered an error in the browser console: Uncaught TypeError: Cannot read property 'func' of undefined at Object../node_modules/react-router/lib/InternalPropTypes.js (InternalPropTypes.js: ...

IE encounters issues when dealing with JSON

Using this snippet of javascript along with a json string to transmit data to a flash project. var flashvars = { xmlFile: 'http://iyt.psu.edu/xml/abington/home.xml', preface: 'http://iyt.psu.edu/', preload: '{"url":"f ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

Guide to transferring a Django text field to an HTML attribute and accessing it with JavaScript

Looking to transfer a caption from a Django template to JavaScript for an image? Below is the relevant portion of the HTML code: <ul id="portfolio"> {% for picture in gallery_selected.photo_set.all %} <li><img src={{ picture.path }} a ...

Struggling to link together a series of axios requests

So here's the plan: I want to make an axios.get() request to pull specific data using a particular id, then use that id as a string literal for my second request. However, I keep running into issues with the "Info is not defined" error message. axio ...

Exploring Angular and Node.js to Retrieve Image Dimensions

I'm struggling to figure out the most effective method for determining the image dimensions or naturalWidth of images based on their URL, usually found in the src attribute of an <img> tag. My objective is to input a URL of a news article and u ...

Create a variety of URL formats for various object cases

Can you guide me on how to verify and create a URL under different circumstances? I am dealing with 3 cases that involve different types of objects: "repositories": { "toto": { "tata": "https://google.com/", ...

Jquery refuses to load

Hey everyone! I'm currently working on an HTML file for my Angular 2 course. After setting up the dependencies and downloading them with npm, I encountered an error when trying to run the app... The error message I received was: file:///Users/Rocky/A ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Generate checkboxes within a For loop and connect their values using Vue JS

I am currently working on setting up filters to sort through data from a database by using multiple checkboxes in combination. The goal is something similar to this: https://i.sstatic.net/woGkR.png After being redirected from a landing page, I arrive at ...

Strategies for refreshing jQuery DataTable after clicking a link without leaving the current page

Within my jQuery datatable, I have a column that displays a green checkmark link if the data is true, and a red X link if the data is false: { data: "HasPayment", render: function (data, type, row) { var paymentSet = '@Url.Action("Set" ...

Is There a Sparse Array Element in JavaScript?

Is there a more efficient method to check for the presence of an array element within multiple layers of a structure? For example: if (typeof arr[a][b][c] === 'undefined') { ...do something... } If [a] or [b] are missing, we cannot accurately t ...

Text disappears from navbar after selecting anchor link

Recently, I've been experimenting with Twitter Bootstrap and have found it to be quite delightful. I managed to create a fixed navbar that sits at the top of my website. Inside this navbar, you'll find my logo, a header, a few links, and a dropd ...

The script remains static and does not alter the "href" or "div" content based on the current URL

I am having an issue with my NavMenu on my website. It is a table with images that link to product pages, and I want to change the links and names based on the language of the site. However, the script I wrote for this is not working properly. I have tried ...

Chrome experiencing problems with placeholder text fallback event

My text field has a placeholder text that says "First Name". When the user clicks on the field, the text disappears and allows them to type in their own text. HTML <input class="fname" type="text" placeholder="First Name"/> JS function handlePlac ...