Pug does not have access to computed properties within the dynamic class attribute of a Vue component

After attempting to dynamically toggle the className based on computed property and encountering issues in Pug, I found that manually setting 'true' to a className was the solution. Even after trying to reassign the computed property to a Pug variable, it still did not work.

In contrast, using pure HTML allowed for classes to dynamically toggle correctly.

Pug:

main#app.container
  - var isPinkDefinitely = isPink ? 'pink' : 'gray';
  div.section(
    v-bind:class=[
      'custom-section',
      {
        'custom-section--pink': isPink
      }
    ] 
    v-bind:style=[
      {
        'background-color': isPinkDefinitely
      }
    ]
  ) {{ isPink }}
    form(@submit.prevent="addItem")
      label.label Add another
      div.field.has-addons
        div.control
          input.input(required, autofocus, v-model="newItem", placeholder="Remake this in React")
        button(type="submit").button.is-info
          i.fa.fa-plus
          span Add

    transition(name="slide")
      div(v-show="items.length > 0")

        hr

        ul
          transition-group(name="slide")
            li(v-for="(item, index) in items", :key="item.id")
              button(@click="removeItem(index)").button.is-danger
                i.fa.fa-trash
              span(v-text="item.desc")

        hr

        span(v-text="'Total: ' + items.length")

JS:

new Vue({
  el: '#app',
  data: {
    items: [
      {id: 1, desc: "Lorem"},
      {id: 2, desc: "Ipsum"},
      {id: 3, desc: "Dolor"},
    ],
    newItem: '',
  },
  computed: {
    isPink() {
      return true;
    }
  },
  methods: {
    addItem () {
      const id = this.items.length + 1
      this.items.push({id, desc: this.newItem})
      this.newItem = ''
    },
    removeItem (index) {
      this.items.splice(index, 1)
    },
  },
})

https://codepen.io/itprogressuz/pen/qBoePob?editors=1010


UPD: SO the basically solution was to just write all classes in one line inside just an object. see solution of @aykut

Answer №1

After tackling the issue at hand, I believe I have successfully resolved your problem by utilizing variables effectively. By incorporating them into computed functions, you can observe dynamic changes in real-time. Additionally, methods functions can be employed to modify these variables based on user interactions. Below is the solution I have devised:

main#app.container

div.section(
class="default-style"
:class="{'bg-pink': isPink }"

) {{ setIsPink }}
form(@submit.prevent="addItem")
  label.label Add another
  div.field.has-addons
    div.control
      input.input(required, autofocus, v-model="newItem", placeholder="Remake 
this in React")
    button(type="submit").button.is-info
      i.fa.fa-plus
      span Add

transition(name="slide")
  div(v-show="items.length > 0")

    hr

    ul
      transition-group(name="slide")
        li(v-for="(item, index) in items", :key="item.id")
          button(@click="removeItem(index)").button.is-danger
            i.fa.fa-trash
          span(v-text="item.desc")

    hr

    span(v-text="'Total: ' + items.length")

// css file

.default-style{
background-color: gray;
}

.bg-pink{
    background-color: pink;
    }

// js file

new Vue({
  el: '#app',
  data: {
   
    isPink: false,
    items: [
      {id: 1, desc: "Lorem"},
      {id: 2, desc: "Ipsum"},
      {id: 3, desc: "Dolor"},
    ],
    newItem: '',
  },
  computed: {
    setIsPink() {
      this.isPink = !this.isPink;
      return this.isPink;
    }
  },
  methods: {
    addItem () {
      const id = this.items.length + 1
      this.items.push({id, desc: this.newItem})
      this.newItem = ''
    },
    removeItem (index) {
      this.items.splice(index, 1)
    },
  },
})

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

Passing values from a Laravel controller to a Vue component as a prop

At the moment, I have a Laravel route that directs to the index function of my controller with an ID passed, where I then return the ID in a view. public function index($id) { return view('progress') ->with('identifier', ...

"Maximizing the potential of a single domain by hosting multiple websites with distinct paths such as domain.fr/siteA, domain.fr/siteB, and domain.fr/siteC using Docker in conjunction with

Just curious about the distinctions between import { getContent } from '@/assets/welcome-content.js' import Navigation from '@/components/Navigation' and import { getContent } from '~/assets/welcome-content.js' import Navigat ...

I'm looking to customize the background color and font size for an accordion in Bootstrap 4 with Vue.js. Can anyone provide guidance

Hello, I am currently using an accordion with Bootstrap 4 and Vue.js. Here is the code snippet: <div class="faq_accordion" role="tablist"> <b-card no-body class="mb-1"> <b-card-header header-tag=" ...

Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route t ...

Is it possible to include HTML in a response when verifying emails with Node JS and Angular?

Before diving in, I want to make it clear that I have experience using APIs created in NodeJS with Angular. However, I am encountering a bit of a challenge. The issue at hand involves a function that verifies the email used during registration: exports.co ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

List of null variables

I'm having trouble grasping the concept of an array filled with empty values like this: let arr=[,,,]; When I attempt to log the length, it shows 3 instead of 4. let arr=[,,,]; console.log('length',arr.length); console.log('arr[1]&a ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

Is it possible to use jQuery to load an HTML file and extract its script?

I have a navigation bar with five buttons. Whenever a button is clicked, I want to dynamically load an HTML file using AJAX that includes some JavaScript code. The loaded file structure resembles the following: <div> content goes here... </div& ...

Having trouble getting my Node.js Express code to display 'Hello World' on Cloud 9 platform

Recently, I've been experimenting with Cloud 9 and have been encountering an issue while trying to execute the sample code provided on the Express website to display 'Hello World!'. I have attempted listening on various ports/IP addresses ba ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Can one create this structure in VueJS when using v-for directives?

Consider a scenario where there is a collection of objects stored in the data property of a component: data: function () { return [ { id: 1, name: "foo", br: false }, { id: 1, name: "bar", br: true }, { id: 1, name: "baz", br: false } ] } ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

What is the process for modifying the characteristics of an RMWC Component?

How can I dynamically change the icon attribute in my RMWC Button element when an onClick event occurs? <Button outlined icon={<CircularProgress />} onClick={(e)=> { // e.currentTarget.icon = ''; // console.log(e.c ...

Verify the validity of the token before making the request

In my Vue app, I am utilizing an index.js file to handle API calls. I am wondering if there is a way to implement a catch or a before each call function that checks if the user's token is still valid. If the token is expired, I would like to redirect ...

vue-spa breadcrumbs component

I am currently working on enhancing the navigation of my vue-spa project by implementing breadcrumbs. These breadcrumbs should be capable of displaying properties as breadcrumb-items, and each part of a route must be correctly identified as a breadcrumb-it ...

Caution: React alert for utilizing the UNSAFE_componentWillReceiveProps in strict mode

As a newcomer to React, I encountered a warning that has me stuck. Despite researching extensively online, I still can't resolve it. The warning message is: https://i.stack.imgur.com/4yNsc.png Here are the relevant portions of the code in App.tsx: ...

Unraveling AngularJS: Mastering the Art of Interpolating Interpol

Trying to interpolate a string retrieved from the database, such as "Users({{users_count || 0}})", poses a problem. Using {{}} or ng-bind for interpolation does not work properly. The HTML code written is {{data.usersCount}}, but instead of ren ...

The functionality of the remove button in the jQuery Dropzone seems to be malfunction

I devised a user-friendly drag and drop feature for uploading images using the dropzone plugin. Here is the code snippet that I implemented: <script src="<?php echo base_url() ?>acc/assets/dropzone/dropzone.js"></script> <form actio ...