Using props in Vue with CSS modules: A comprehensive guide

row.vue

<script>
  export default {
    name: "Row",
    data() {
      return {
        app: [
          "row",
          "row-test",
          "flex-center"
        ]
      }
    },
    template: `
      <div :class="$module[app]"><slot></slot></div>
    `
  }
  </script>

row.scss

.row {
  color: red; 
}
.row-test {
  color: green; 
}
.flex-center {
  align-items: center;
  justify-content: center; 
}

App.vue

<template>
  <div id="app">
    <row app="row-test flex-center">my row</row>
    <router-view />
  </div>
</template>

vue.config.js

css: {
  requireModuleExtension: true,
  loaderOptions: {
    css: {
      modules: {
        localIdentName: 'hex-[HASH:HEX:3]'
      }
    }
  },
  modules: true
}

I aim to set attributes using the app attribute, treating them like regular classes. These values will be stored in an array inside row.vue and applied as CSS properties using CSS modules (a randomly generated class is assigned).

The issue I'm facing

<div app="row-test flex-center">my row</div>

Desired outcome

<div class="hex-g3D hex-f41">my row</div>

Answer №1

In order to pass the app as a prop to the Row component, you will need to create a computed property that returns modules with different classes:

<script>
  export default {
    name: "Row",
   props:['app'],
  computed:{
   modules(){
     return this.app.length? this.app.map(_class=>{
            return this.$module[_class];
      }):[];
    }
  },
    template: `
      <div :class="modules"><slot></slot></div>
    `
  }
  </script>

To use it, pass the following code:

<template>
  <div id="app">
    <row :app="['row-test', 'flex-center']">my row</row>
    <router-view />
  </div>
</template>

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

Navigating to the parent Vue component in a Vue3 project with Composition API structure in WebStorm

After transitioning to Vue3 and embracing the Composition API style, I find myself missing a small convenience that I had when developing in the previous Options API pattern. In WebStorm/IntelliJ IDE, I used to be able to command-click (Mac) on the "export ...

Tips for updating a specific field within an object in an array within a mongoose schema and persisting the changes

I am currently developing a website where users can sign in, create tasks, and mark them as done. I am using mongoose to work with the data, specifically saving tasks inside an array of type Task in a User model. Each task has a "done" value which is repre ...

Ensuring website responsiveness beyond just the carousel

I found a carousel (inspired by: https://codepen.io/dobladov/pen/kXAXJx) that fetches images from an API. The carousel will switch images as you click on a different image or use the "previous" or "next" buttons. While there are many examples of putting te ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

Looping through required fields in jQuery based on a CSS class

Is there a way to loop through required fields marked with <input class="required">? Currently, only the first input in the loop is being evaluated. How can I traverse the DOM using a loop to check all input boxes? Thank you for your help. While I ...

A fresh perspective on incorporating setInterval with external scripts in Angular 7

Incorporating the header and footer of my application from external JavaScript files is essential. The next step involves converting it to HTML format and appending it to the head of an HTML file. private executeScript() { const dynamicScripts = [this.app ...

Ways to personalize php artisan ui vue --auth templates

Hello, I have a question about customizing the routes and files generated when using php artisan ui vue --auth. Is it possible to edit these files to add additional steps or customize the registration process? I noticed that the web.php file does not sho ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Vuex: Unable to pinpoint why my getter is failing to sort correctly

store.js getAllCommentsOrderedByTimestamp(state) { let allComments = state.allComments; allComments = allComments.sort((a, b) => { return a.stamped > b.stamped; }); return allComments; } allComments is an array of objec ...

How to align the horizontal title of the yAxis in HighCharts

I have two charts with different yAxis titles. I am trying to align the titles horizontally to the right side of the chart (on the left side of the Y line). However, the alignment only seems to work vertically centered. I actually need the titles to be in ...

Accessing HTML files locally in an offline web application: A step-by-step guide

I am currently in the process of developing a mobile web-based game. My goal is to implement a single-page design that can be accessed offline. I am looking to organize and store various HTML pages as files within a designated folder, and load them into a ...

Updating the content of a file on an iPhone

Is there a way to update the entire document content with a response from an ajax request? I've tested out using document.body.innerHTML and document.write(), which both work on desktop Safari. However, I'm looking for a solution that will also ...

Retrieving information from jQuery object using jQuery

I am utilizing ajax to retrieve information from the database. Once I have retrieved the information from the table, I am using json_encode to format the data into JSON. Then, I am utilizing parseJSON to display the data in JavaScript. After receiving the ...

What is the best way to route a Single Page Application in a separate route within an Express application that has

Imagine having a traditional blog built on Express, but now you want to add a Vue.js-powered blog content manager as a Single Page Application. You're looking to serve this new app from a unique route like https://myapp/admin/dashboard while keeping ...

Retrieve an image from an external web service and transfer it to a different route in Express.js

I am facing an issue with passing an image object from an external web service through a node express route. The specific problem I am encountering involves retrieving an image from a URL and attempting to pass it as is, but it seems to be not functioning ...

JavaScript throws a "null is null or not an object" error when attempting to

I am dealing with a div that contains flash content in the form of Open Flash Chart. However, I encounter a javascript error when trying to remove child divs using $("#mydiv").children().remove() specifically in IE 8: The error message reads: "null is n ...

Obtain the key's value from a JSON object that is nested within another

Managing a complex data structure is crucial in programming. How can I efficiently retrieve specific values using known keys from this nested data? Take, for instance: var data = { code: 42, items: [{ id: 1, category: [{ ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...