Add a class by utilizing the :class attribute

I reviewed the documentation, but I am still struggling to implement this in my project. Initially, I simply want to display a specific class using vue.js that I can later modify dynamically. I just need to establish the default behavior of that class, so I attempted the following:

HTML

<div class="row">
       <h1 class="text-center title"></h1>
       <div class="col-md-offset-1 col-md-10">
          <div :class="progressYou">asd</div>
       </div>
    </div>

    <div class="row">
        <div class="col-md-offset-1 col-md-10">
            <div :class="progressMonster">asd</div>
         </div>
    </div>
    

CSS

.progressYou{
        width: '100px';
        background-color: 'green';
        height: '50px';
    }

    .progressMonster{
        width: '100px';
        background-color: 'green';
        height: '50px';
    }
    

Javascript

new Vue({
        el: '#monsterGame',
        data: {
            incrementMonster: 0,
            incrementYou: 0,
            progressMonster: {
                'width': '100px',
                'background-color': 'green',
                'height': '50px'
            },
            progressYou: {
                'width': '100px',
                'background-color': 'green',
                'height': '50px'
            }

        }
    })
    

Does the CSS file need to be linked? Essentially, I want to create a class in my CSS and dynamically alter it using the objects defined in the JavaScript data section, but nothing is appearing on the screen. What could be the issue here?

Answer №1

Your usage of the `v-bind:class` directive is incorrect as you are passing style specifications instead of classnames.

Additionally, there are unnecessary quotes in your CSS code.

new Vue({
  el: '#monsterGame',
  data: {
    incrementMonster: 0,
    incrementYou: 0,
    className: 'progressMonster'
  },
  methods: {
    toggleClass: function () {
      this.className = this.className === 'progressMonster' ? 'progressYou' : 'progressMonster';
    }
  }
})
.progressYou {
  width: 100px;
  color: white;
  background-color: green;
  height: 50px;
}

.progressMonster {
  color: black;
  width: 100px;
  background-color: lightblue;
  height: 50px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<div id="monsterGame">
  <div class="row">
    <h1 class="text-center title">YOU</h1>
    <div class="col-md-offset-1 col-md-10">
      <div :class="[className]">asd</div>
    </div>
  </div>

  <div class="row">
    <div class="col-md-offset-1 col-md-10">
      <div :class="[className]">asd</div>
    </div>
  </div>
  <button @click="toggleClass">Switch</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

NPM is complaining about the absence of a start script

Apologies for any language barriers in my English. I'm currently facing an issue while trying to deploy an app on Heroku using the heroku local web command in the terminal. The error message ERR! missing script: start keeps popping up, even though the ...

Creating a triangle with SVG polygon: A step-by-step guide

I'm attempting to create a bottom triangle using SVG polygons, similar to the image below: https://i.stack.imgur.com/571FM.png Here is what I have tried so far: <svg xmlns="http://www.w3.org/2000/svg" height="150px" width="100%" viewBox="0 0 ...

Sending JSON data to the server using jqGrid: A step-by-step guide

[CHANGE] (I couldn't bear to wait 3 hours for an answer): It seems that the issue is not with the jqGrid component, many thanks to TheCodeDestroyer for identifying this. I ran this code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "h ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

What is the best way to show HTML code from an HTML file in a Vue template?

I need help showcasing the HTML code from an external file in a Vue component template. <template> <div class="content"> <pre> <code> {{fetchCode('./code/code.html')}} & ...

I am puzzled by the fact that the data stored in Vue.js Vuex using Firebase is not accessible when reloading the page in

When a user hits the reload button on the web browser, I am unsure of what exactly happens... After logging in for the first time, it is fine to display user data. The store state data and caching data from localStorage are accessible. However, upon reloa ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...

Exploring the possibilities of combining OpenCV with web technologies like Javascript

I am currently faced with the challenge of integrating OpenCV into a web application using Express.js. While I am familiar with the Python and C++ libraries for OpenCV, I now need to work with it in conjunction with Express.js. My main requirements include ...

An error occurred while trying to load the resource in the Redux-Saga: connection refused

Utilizing axios allows me to make calls to the backend server, while redux-saga helps in managing side effects from the server seamlessly. import {call, put, takeEvery} from "redux-saga/effects"; import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_U ...

Activate animation when a user clicks on a link

Hey there, I'm a bit unsure about how to word this and I'm still getting the hang of StackExchange so I hope I've posted in the correct place. Currently, I am developing a mobile HTML5 app that utilizes Phonegap/Cordova (as well as Bootstra ...

Arranging elements using the ng-repeat directive in AngularJS

My question pertains to an array I am working with: $scope.answers=["","","",""] This array contains several empty elements. <li ng-repeat="item in answers "><input type="text" ng-model="item"/></li> When running this code, an error i ...

Guide to creating an uncomplicated quiz using PHP

My goal is to create a quiz with 15 questions. Every time a user lands on the page, they will see a random selection of 5 questions. Each question will have 4 multiple choice answers, with one being correct. The marks allocated for each question are 20, 15 ...

Changing <br> to a newline ( ) using JSOUP

Is there a way to efficiently replace all occurrences of <br> with a new line character (\n) in HTML using Jsoup? I'm looking for a clean solution that will result in the Element#text() outputting plain text without any HTML, but with &bsol ...

Creating an installation-ready Progressive Web App with Vue.js: A step-by-step guide

I am looking to add the functionality of installing my Vue app as a PWA in Chrome or Firefox with the click of a button. <button @click="install">install</button> var deferredPrompt methods: { install() { deferredPrompt.promp ...

The system encountered an error stating that the required component "Footer" in the main directory was not located in the specified node_modules

Issue I'm Facing: Error found in components/main/Footer within the file path: ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue Components Tree as shown in the screenshot below: Cod ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...