Binding data conditionally based on a property in Vuejs

My situation involves a component that includes a child component with bindable properties. Here is an example:

<template>
  <div>
    <Child :bar="foo"></Child>
  </div>
</template>
<script>
export default {
  name: 'Parent',
  props: ['foo'],
}
</script>

What I am looking to do now is conditionally bind the 'bar' property of the Child component. Specifically, I only want to bind the 'bar' property if the 'foo' property from the parent component is not undefined. How can I achieve this?


To those who suggested using the v-if directive:

I believe that using the v-if directive is not the best solution. If conditions become complex and there are multiple properties that need to be conditionally bound (e.g., 5 properties), the code will become unwieldy with a long chain of if-elseif-else statements. This approach is not ideal.

I am curious if there is a way to solve this problem in a manner similar to React - manipulating the virtual DOM and handling binding programmatically. However, I have not found any API function that functions similarly to the v-bind directive on a child component in the render function.

Answer №1

One way to conditionally render components is by using v-if:

<div v-if="foo">
  <Child :bar="foo"></Child>
</div>
<div v-else>
  <Child></Child>
</div>

Although, it's advised not to render conditionally if possible. Instead, you can simply check if the bar prop is not undefined.


An alternative approach:

You can make use of v-bind with an object for your situation:

<Child v-bind="{bar: foo || '' }"></Child>

Another option is to try leveraging ES6 features like this (though unsure if it will work as expected):

<Child v-bind="...(foo && {bar: foo})"></Child>

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

Encountered a POST Error while attempting to access a backend function from the frontend in a React application, resulting in

I have developed a website using React for the frontend and Node.js Express for the backend. However, I am facing an issue where calling a backend function from the frontend takes around 2 minutes and results in the following error being displayed in the c ...

Retrieve the highest 10 values from a JSON document using jQuery

I am working with a JSON file in my jQuery project, and I need to display only the top 10 values with the highest numbers. For instance: JSON: { "value": { "number": "12", "number": "11", "number": "10", "number": "9", "number": "8", ...

Leveraging the power of AJAX, PHP, and JavaScript to display numerous status updates throughout an extended operation

It has come to my understanding that when using PHP, it is not feasible to send messages to the DOM using AJAX as the entire script must finish executing before the response becomes available. This leaves me with two possible solutions: Break down the le ...

I'm looking for guidance on effectively utilizing filter and map within the reducers directory to manipulate the workouts objects

I am encountering an issue while trying to send delete and update requests for the workout object. The error message indicates that the filter function is not compatible as it's being applied to an object instead of an array. Here is the snippet of co ...

Need help adding color to your PlotlyJS barpolar chart background?

After creating a PlotlyJS barpolar chart, I noticed an issue with the background color where the bars end. The background color seems to be stuck on white, as shown in the image. (Please ignore the transparent black rounded square in the background, as it ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

Updating HTML using Angular JS with a nested dictionary is a breeze

As a newcomer to AngularJS, I am facing an issue with my code. I have created a dictionary in the controller scope and populated it after an HTTP request (key, value pair). The dictionary is being created successfully and there are no errors, but the HTML ...

I've encountered a peculiar error that is new to me while using bootstrap and javascript. Can anyone shed light on what this error signifies?

Hey there! I've come across this error in the console while attempting to utilize Bootstrap. It seems that a style is being refused from 'http://127.0.0.1:5500/node_modules/font-awesome/css/font-awesome.min.css' due to its MIME type ('t ...

Running Jasmine asynchronously in a SystemJS and TypeScript setup

I am currently executing Jasmine tests within a SystemJS and Typescript environment (essentially a plunk setup that is designed to be an Angular 2 testing platform). Jasmine is being deliberately utilized as a global library, rather than being imported vi ...

Enhancing the default vue-cli webpack app with additional components

To ensure reproducibility, I began by setting up a basic project using vue-cli: npm install -g vue-cli vue init webpack spa cd spa npm install npm run dev Afterwards, I decided to swap out the Vue logo with an app-header component. Here's how I impl ...

Use Google script to input drop down options directly into a Google spreadsheet

After gathering coding advice from various StackOverflow examples, I've hit a roadblock while attempting to take my script to the next level. The task seems simple enough, but for some reason, I just can't figure it out. Here's the situati ...

Sending a jsp page for review at specified intervals

Using the setTimeout method, I attempted to achieve this. I passed a variable containing time as an argument, but the setTimeout method is only taking the initialized value of that variable and not the updated value fetched from the database. Below is the ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

Toggle visibility of div based on current business hours, incorporating UTC time

UPDATE I have included a working JSFiddle link, although it appears to not be functioning correctly. https://jsfiddle.net/bill9000/yadk6sja/2/ original question: The code I currently have is designed to show/hide a div based on business hours. Is there a ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Implementing Google Ads Code in NextJS for Automated Units

I'm currently working on a NextJS project and I need to integrate the Google AdSense code for automatic ads. The Google ad code I have is: <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env. ...

Resolving the Issue with onClick Events in Closures

Secrets of the JavaScript Ninja provides an interesting example: HTML <button id="test">Click me!</button> JavaScript var button = { clicked: false, click: function() { this.clicked = true; console.log("this:", this, ...

What is the best way to create operating system-neutral file paths in Node.js?

I'm currently fixing issues with my code while running integration tests on an EC2 instance of a Windows machine. Despite resolving the filenames-are-too-long problem, several paths remain unresolved due to being hardcoded for UNIX systems. I've ...

Creating interactive click and model expressions in AngularJS

Within my ng-repeat loop, I am trying to implement the following toggle functionality: <a href='#' ng-model="collapsed{{$index}}" ng-click="collapsed{{$index}}=!collapsed{{$index}}">{{item.type}}</a> <div ng-show="collapsed{{$in ...

Unable to retrieve data in Vue using Axios for GET request

Recently delving into Vue, I'm struggling to figure out what's causing the issue in my code. Here's a simple component snippet: <template> <template v-if="loading"> Loading... </template> <te ...