Passing inline CSS styles from parent component to child component in Vue

I am currently using vue.js with vuetify, and I need to position a button on top of a canvas component (managed by the Konva library).

I successfully achieved this by using absolute positioning for the button. However, in order to organize my code better, I want to place this button in a separate dedicated component.

My goal is to pass the positioning CSS inline to this new child component, but I am struggling to make it work.

I have attempted two approaches:

  • Trying to pass it with a :style="xxx" binding, similar to how I did it when using v-btn directly
  • Passing the positioning to a parent div: this works if the div has a width != 0, but it feels like a workaround. Additionally, in this case, the z-index property is not applied to the button.
  • I could pass the attributes with a specific prop, but it seems that vuetify does not require it

Below is a snippet of my code:

<template>
  <v-container fluid fill-height ref="parentLayout" class="pa-0" :style="{position: 'relative'}">
    <div ref="konvaLayout" :style="{backgroundColor:'rgb( 40, 40, 40 )'}">
      <!-- This works /-->
      <v-btn absolute :style="{top:'10%', left:'10%', width: '100px'}"> THIS WORKS </v-btn>
      <!-- This does not /-->
      <my-button :style="{position: absolute, top:'2%', left:'2%'}" />
  </v-container>
</template>

To summarize, I have the following questions:

  1. How can I correctly bind :style to the child element, similar to how vuetify handles it?
  2. What is the recommended approach for passing CSS position attributes to child components? Is using style binding the standard method as described in question 1?

Thank you everyone for your assistance

Answer №1

One of the key issues in this scenario is akin to what v-deep aims to address in the realm of CSS (though it may not resolve your current issue).

The absence of a native element within the konvaLayout division prevents the style from reaching the intended component.

In the MyButton.vue component, there are two approaches you can consider for resolving this:

- Overwriting with Props -

//MyButton.vue
<template>
  <v-btn :style="style">{{ label }}</v-btn>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    label: String,
    style: [String, Object]
  }
});
</script>

- Using Custom Prop -

Employ a custom prop name that is exclusively designated for styling the button within the my-button context (quite amusing)

//MyButton.vue
<template>
  <v-btn :style="btnStyle">{{ label }}</v-btn>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    label: String,
    btnStyle: [String, Object]
  }
});
</script>

(No guarantee provided as a codesandbox or similar platform was not supplied for validating its functionality)

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

Issue encountered: Framer Motion animation is not functioning properly on elements that are rendered using the map()

I'm attempting to create an animation similar to this: https://drive.google.com/file/d/1WQCg7j49xd5XfuaYuC2YFQCUU-UXassp/view?usp=sharing Here's the code I have: <motion.div layout className="grid grid-cols-2 md:grid-cols-3 gap-8 py-10&q ...

vue-awesome-swiper / The button's name is synchronized, causing all other swiper elements to move in unison

<template> <swiper v-for="item in items" :key="item.id" :options="swiperOption" ref="mySwiper" @someSwiperEvent="callback"> <swiper-slide>I'm Slide 1</swiper-slide> <swiper-slide>I'm Slide 2</swiper-slid ...

What is the method for identifying which input field the user has chosen on a web page retrieved from a server?

I attempted the code below without achieving the desired outcome. Any assistance would be greatly appreciated. UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setString:passwordName]; NSString *jScriptString; jScriptString = [NSString string ...

Looking for assistance with importing OBJ and MTL files into Three.js?

I'm encountering a strange issue while attempting to load an OBJ and MTL file in Three.js using the OBJMTLLoader() function and am unable to find a solution online. My project structure includes an index.html file and a js folder with all the necessar ...

JavaScript not properly rendering CSS styles

If I insert the following HTML statically, the CSS style is correctly applied. HTML: <li class="connector"> <a href="#"> <img src="css/images/temp/connector2.png" alt="" width="192" height="192"> <span class="sr-only"& ...

Why isn't my ng-click function functioning properly on Google Maps in AngularJS?

i have two stores in my database and am attempting to display them on a Google map with markers. I have an ng-click function inside the info window to pass the store id, but it seems like ng-click is not working. Is there any alternative method to pass t ...

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

AngularJS Issue: Duplicate Error

Attempting to refresh data after making some changes results in duplicate errors appearing within the ng-repeat. The scenario is as follows; I am working on creating a dynamic menu module The requirements include adding, deleting, changing the order, an ...

Choose Your Price - Price Grids

I need to incorporate two sets of pricing columns into a website. The first set is for regular car cleaning prices, while the second set is for larger cars with slightly higher prices. My idea is to have two buttons at the top – one for regular cars and ...

Floating action button within a collapsible panel

I am having trouble placing a fixed-action-btn inside a collapsible body. It keeps appearing in the bottom right corner of the page instead of within the collapsible itself. How can I ensure that the button stays inside the body? Check out this link for r ...

Troubleshooting a CSS problem with iPad browsers

I have a specific issue related to CSS on iPad. I am working with a set of sublinks and have defined the styles in CSS as follows: #leftNav .searchBySub {...} #leftNav a.searchBySub:hover {...} #leftNav .searchBySubClicked {...} In my JavaScr ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

What is the process for storing an array in AdonisJs migrations?

Having trouble saving an array into a PostgreSQL database! 'use strict' const Schema = use('Schema'); class UsersSchema extends Schema { up () { this.create('users', (table) => { table.increments(); t ...

Retrieve the HTML structure from an AJAX response

I'm working on an Ajax call in my code: callAjaxController: function(){ var url = Routing.generate('ajax_price'); $.ajax({ type: "GET", url: url, cache: false, success: funct ...

What is causing my grayscale function to only impact part of the canvas?

As a beginner programmer, I have been experimenting with creating a grayscale function in JavaScript for practice. This is the code I have come up with: <canvas width='400' height='400'></canvas> <script> var can ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

What is the best way to transfer information between two views in Aurelia?

I have two different perspectives, one called logo and the other called folder. The logo view should display something from the folder view if the folder is empty. logo.html <template> <require from="company-assets/folders"></require> ...

Asynchronous operations in Node.js with Express

Hey, I'm still pretty new to using async functions and I could really use some help understanding how to pass callbacks in async.each for each item to the next level (middleware). Here's the logic: I want to iterate through all items, and if an ...

Ways to make an AngularJS Expression show an empty value

Consider the following HTML snippet: <p>{{ booleanVariable ? "The variable is true!" : "" }}</p> In case 'booleanVariable' evaluates to false, the expression should display nothing and the <p></p> tags should not be show ...