A computed property declared inside a Vue component definition

I'm currently diving into Vue.js 2 and I have a goal of crafting a unique custom component in the form of

<bs-container fluid="true"></bs-container>
. My intention is for Vue.component() to seamlessly handle the bootstrap 3 container classes based on the boolean value passed in the fluid prop. This way, the code will appear much cleaner with
<bs-container fluid="true"></bs-container>
rather than
div class="container-fluid></div>
. Although I've made an attempt, it seems not to be functioning as expected:

HTML:

<div id="app" >
<bs-container fluid="false">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</bs-container>

JS:

Vue.component('bs-container',{
props: ['fluid'],
template: '<div :class="setClass"><slot></slot></div>',
computed: {
    setClass: function() {
        console.log('setClass has been called');
        if (this.fluid == true) {
            return 'container-fluid';
        } else{
            return 'container';
        }
    }
}
}); 
new Vue({
        el: '#app'
});

The setClass method does not seem to be triggered. What might I be overlooking?

Answer №1

To create a dynamic binding for the class, use computed properties. Check out this link for more information: https://v2.vuejs.org/v2/guide/class-and-style.html. Additionally, it's advisable to compare strings directly to avoid unnecessary truthy/falsy conversions.

Vue.component('bs-container',{
props: ['fluid'],
template: '<div :class="setClass"><slot></slot></div>',
computed: {
    setClass: function() {
        console.log('setClass has been called');
        if (this.fluid === 'true') {
            return 'container-fluid';
        } else{
            return 'container';
        }
    }
}
}); 
new Vue({
        el: '#app'
});

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

We are sorry, but the requested route cannot be located

I'm diving into the world of express and trying to set up subroutes for a specific "plan" with corresponding actions. My journey begins at mypage.com/someroute/123321312 router.get('/:planId', function(req, res, next) { //a form is render ...

Guide to switching content within a DIV when the up and down buttons are pressed using JavaScript and jQuery

I have a functional code with a timeline where each event is connected to the other. There are buttons to delete and copy data, but I want to implement functionality for swapping elements when the up or down button is clicked. I have provided a sample code ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

Node.js Express application: Managing endpoint conflicts

After searching for a solution to this issue and not finding one, I apologize if this question is repetitive. In my express+node.js application, I have two endpoints defined as follows: // Retrieves a tweet by unique id app.get('/tweets:id', fu ...

Loading an Angular2 app is made possible by ensuring that it is only initiated when a DOM element is detected

In my main.ts file, the code below is functioning perfectly: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); H ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

Insert a zero in front of any single digit hour

What is the best way to add a leading zero before single digit numbers in time format? For example, how can we convert "0:3:25" (hh:mm:ss) to "00:03:25"? ...

Experience the impact of a lagging network connection on Chrome extensions through the power of React-NextJS

I'm currently working on a Chrome extension that requires me to limit download speeds in the browser programmatically (client-side). Despite researching extensively on the subject, I have not been able to find any information on how to achieve this us ...

Initial request fails to retrieve cookie generated by Javascript

I created a shopping cart that generates a cart, adds items, and stores it in a cookie named 'cart'. However, when I click on a hyperlink that leads to the checkout page, my ASP.NET application is unable to access the cookie. The cookie only get ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Exploring the functionality of jQuery's html() method through multiple interactions

I am currently experimenting with this demo. I'm investigating why the HTML content disappears after using the second button. Everything works fine as long as you only click on btn #from-content-1 or only on #from-content-2. But if you click on #from ...

What is preventing the item from being added to the user's 'products' field in MongoDB using the $push command, even though the post was successfully made?

My goal is to seamlessly add a product and assign it to a customer's account by inserting it into the 'products' array in the database. I have opted to utilize the customer's email address, as the frontend interface simply requires an ...

Node.js threw an error when trying to download a tarball, displaying a status code of

While attempting to install various modules in Nodejs using NPM, I encountered a situation where the installation process failed and returned an error: Error: 403 status code downloading tarball This same issue happened again when I tried to install node ...

Commitment to provide the outcome of the second promise in case the first one encounters

I am trying to handle the scenario where I need to return the value of a second promise if the first one (value in cache) fails. Below is my code snippet, but I'm encountering an issue where 'resolve' is not defined. exports.getConfig = fu ...

Problem with Pinia: nested array in an object

My unique store located within a vue3 application, contains an object called currentReservation with a property named pricings which is an array. Each pricing includes an id and quantity. When I add a new pricing, it is added to both the store and compone ...

Apply a unique design to a class by clicking on a button

There are 3 identical boxes with the same classes and a button: function changeColorAndAddPadding() { /* ??? */ } .box { border: 1px solid; display: inline; } <button onclick="changeColorAndAddPadding();">Click Here</button> <d ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Experiencing issues utilizing vue.js to retrieve information from a REST API

Using vue.js, I am attempting to fetch data from a rest api but encountering issues. Unfortunately, the response data is not being displayed and no error status is shown either. It's puzzling trying to identify what may have gone wrong. Below is my i ...

How can I resolve the issue of the input field added dynamically by JavaScript not appearing in the PHP $_POST variable?

I have a form nested within an HTML table. Using jQuery, I am dynamically adding input fields to the form. However, when I submit the form and check the $_POST array with var_dump(), the added fields are not showing up. Why is this happening? Below is th ...