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

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Challenges with NPM testing

Are there any reported issues with npm on Ubuntu 18.04? Or are there known solutions to the 100:1 error? I am currently enrolled in a course and it's crucial for me to be able to execute code using npm test. Despite multiple attempts at deleting and ...

Having trouble accessing the URL route by typing it in directly within react-router?

Having some trouble getting dynamic routes to work with react router. Whenever I enter a URL like localhost:3000/5, I receive the error message "cannot GET /5". Here is how my router is configured: class App extends Component { render() { retu ...

Implementing a universal header using ofetch in Nuxt 3

The objective is to establish a universal header for all outgoing queries Given the latest recommendation to avoid using axios in Nuxt 3, I decided to transition to Nuxt 3's ofetch. However, it seems that the Nuxt 3 team did not include an option to ...

Next js is repeatedly calling a Firestore document in multiple instances during the fetching process

In my Next js 13 project, I am facing an issue while fetching a single document with an id from Firebase. Instead of returning just one read (which is expected since I'm fetching a single doc), it is returning multiple reads, sometimes ranging from 2 ...

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...

Navigating with firebase authentication and angular routing

Currently, I am in the process of developing an ionic app using version 4. For this project, I have decided to utilize firestore as my database and implement firebase-authentication for user login and registration functionalities. However, I have encounter ...

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Sending data from an AngularJS frontend to a Laravel backend using an HTTP

I've been researching, but I can't seem to make sense of anything. I'm new to Laravel and I want to use it as a backend for my AngularJS project. Since I have experience with Angular, here is the controller function where I make an HTTP call ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

A guide on displaying an array object in a table column using Vue.js and Element UI

Having issues with rendering array data in Vue Js Element UI using the el-table-column element. The string data displays correctly, but I'm facing problems with the array data. I've attempted to include static data within the data() return method ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

Invoke OnSelectedIndexChanged from GridView prior to any other function execution

In my scenario, there are two GridViews available. The first GridView allows the user to select a row, based on which a corresponding list will be displayed according to the selected GridView ID. First Grid: https://i.stack.imgur.com/d0OKq.png Second Gri ...