Tips for effectively binding attributes based on conditions in Vue.js

Is it possible to conditionally bind attributes in Vue?

Yes, you can achieve this using the v-bind directive:

Here is an example:

<img :src=" status = true ? 'open.svg' : 'close.svg'">

In Angular, this functionality is available. I am curious if Vue supports it as well.

Alternatively, is there a way to include similar JavaScript code directly in the template using ternary operators?

Answer №1

You have the option to achieve this in two ways:

<img :src="status ? 'open.svg' : 'close.svg'" >

Alternatively, you can make it a computed property like so:

<img :src="imgSrc" >
computed:{
  imgSrc(){
    return (this.status) ? 'open.svg' : 'close.svg'
  }
}

Answer №2

Give this a shot

<img :src="if(status) { 'open.svg'; } else { 'close.svg'; }">

If you have status = true in your code, remember that it is an assignment operator and not a comparison operator. Change it to status == true instead.

Answer №3

You should opt for status == true instead of status = true.

Give it a shot.

var vMain = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    status: true,
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <img :src='status == true ? "https://dummyimage.com/100x100/F00/fff" : "https://dummyimage.com/100x100/0F0/fff"'><br />
  <button onclick='vMain.status = ! vMain.status;'>Switch Status</button>
</div>

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

HTML comments generated from Freemarker's list notation

Currently, I have integrated Apache Freemarker into an HTML editor where users can create templates using code. For example, a user may write the following code for a list: <#list items as item>...</#list> While this is the correct way to gen ...

Learn the process of incorporating hyperlinks into individual table entries with the PrimeVue DataTable component

The default setup of PrimeVue library does not support this feature. Here is how the Table currently appears: example image. Displayed below is an array containing product information: products: [ {brand: "Volkswagen", year: 2012, color: ...

Create a variable and set it equal to the value of a form

I'm having trouble setting a value to a hidden form field that needs to come from a query string parameter. The function that extracts the query string parameter is working properly, but the function that assigns this variable to the hidden form field ...

Manipulating and inserting objects into an array using React and Typescript with an undefined type

As I embark on my TypeScript journey in React, I decided to test my knowledge by creating a simple Todo App. Everything seems to be working fine except for one issue! After adding a new task and hovering over it, I received the following error message (tr ...

The closing brackets in PHP substr() function are causing style issues

Here's the scenario: I entered a large amount of content in a text editor (WordPress). Now, I want to display this content on my homepage using PHP queries. In order to limit the content size to 100-200 characters, I used the substr() function i ...

Removing leading zero from ng-change value in controller

One example of my input field is shown below: <input id="0900" type="radio" ng-model="formData.appointment_hour" ng-change="change(0900)" name="appointment" value="0900" class="ng-valid ng-dirty"> After inspecting the function in my controller, I n ...

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

When utilizing the http.post method, the req.body is not being populated as expected

I am puzzled by the fact that the req.body appears to be empty... app.js utilizes the body-parser middleware() var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/in ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

A configuration for ".node" files is missing: specifically, the loader for node_modules/fsevents/fsevents.node in a project using Vite

Everything was running smoothly in my Vite + React project until last week when out of nowhere, I encountered this error: No loader is configured for ".node" files: node_modules/fsevents/fsevents.node node_modules/fsevents/fsevents.js:13:23: 1 ...

What is the best way to emphasize the current page within my Bootstrap <nav> menu?

Below is the Bootstrap code that defines our main menu navigation: <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> ...

Using inline CSS to apply conditional styles to a component in React is a great way to customize the

I'm currently working on customizing the styles of some buttons depending on their 'active' status and whether the user is hovering over them. So far, it's partially working but I'm encountering behavior that I can't fully com ...

React.js experiencing issues with loading the splash screen

I am developing a Progressive Web App (PWA) and I am currently facing an issue with displaying the splash screen. In my index.html file, I have added the following code to the head section: <link rel="apple-touch-startup-image" media="scr ...

Using React to access a function from a different component in your application

I am working on implementing a topbar menu that requires access to a specific react component. The challenge I am facing is that within the topbar file, I do not directly render the components I need to interact with but still want to be able to call a fun ...

The React OnClick and onTouchStart event handlers are functioning properly on a desktop browser's mobile simulator, but they are not responsive when

I added a basic button tag to my next.js main page.js file that triggers an alert when clicked. Surprisingly, the onClick function is functional on desktop browsers but fails to work on any mobile browser. "use client"; export default function P ...

Sveltejs template not displaying on M1 MacBook Air after running - stuck on blank screen

Currently, I am in the process of learning Sveltejs and have been utilizing for the tutorial, which has been quite effective. However, I decided to work on developing and testing Sveltejs applications locally on my MacBook Air M1. I downloaded the provid ...

Retrieve data from a specific page on a URL using AJAX

window.onload= function(){ var page = window.location.hash; if(window.location.hash != ""){ page = page.replace('#page:', ''); getdata('src/'.page); } } Once the window has loaded, I want to check ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

Unable to retrieve AJAX response

I've been working on a page where I'm using AJAX to fetch data based on the selection of radio buttons. The three options available are 'Unapproved', 'Approved' and 'All'. My goal is to display the corresponding user ...