Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter.

<div class="container"  :style=" textposit(textpos) ">
       <p class="headline">{{ headline }}</p>
       <p class="text">{{ text }}</p>
</div>

Here is my script:

export default {
    name: 'page',
    components: {
    },
    props:{
        headline: {
            type: String,
        },
        text: {
            type: String,
        },
        img: {
            type: String,
        },
        align:{
            type: String,
            default: "center",
        },
        textpos:{
            type: String,
            default: "left",
        },
        textrows:{
            type: Number,
            default: 1,
        }
    },
    methods:{
      textposit (pos){
            if (pos == "left") {
                return{
                    "grid-column: 4 / 5"
                }
            }
            else{
                 return{
                    "grid-column: 1 / 2"
                }
            }
        }
    }
}

I can see that the method is being called, but it's not changing the style of my div. Any help would be appreciated. Thank you!

Answer №1

Furthermore, it can be utilized as a property value in the following manner. (I have included colors for better visualization)

const {
  createApp
} = Vue

const App = {
  methods: {
    textPosition(position) {
      if (position == "left") {
        return "red"
      } else {
        return "blue"
      }
    }
  }
}

Vue.createApp(App).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <div :style="{color: textPosition('left')}">TEXT</div>
  <div :style="{color: textPosition('somethingelse')}">TEXT</div>
</div>

Answer №2

Consider defining it as a computed property instead of a method :

<div class="container"  :style=" textposit">

In your script:


export default {
    name: 'page',
    components: {
    },
    props:{
       //....
    },
    computed:{
      textposit (){
            if (this.textpos === "left") {
                return{
                    "grid-column": "4 / 5" 
                }
            }
            else{
                 return{
                    "grid-column": "1 / 2"
                }
            }
        }
    }
}

I also updated "grid-column: 4 / 5" to

"grid-column": "4 / 5"
to ensure it's a valid object field.

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

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Utilizing jQuery and DOM to interact with form elements

Below is the form content <form method="post"> <input type="hidden" name="resulttype" value="Create"> <table> <tr> <td>Full Name</td> <td><input ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

Tips for cutting down on bundle size in your WEBPACK setup when using VUEJS

I have tried numerous tutorials to reduce the size of my bundle, but none of them seem to be affecting the bundle size and I can't figure out why. Every time I integrate new code into webpack, the bundle size remains unchanged. (The application is c ...

Creating Visuals with CSS Gradients: A Tutorial on Generating Images and SVG Files

I currently have a CSS gradient applied and I am interested in creating an image or SVG file from it. However, I am unsure of how to accomplish this task. Any advice would be greatly appreciated. background: -webkit-linear-gradient(bottom, rgb(211, 208, ...

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Utilizing external Cascading Style Sheets in AngularJS 1

Can an external CSS be applied to a component in AngularJS1? If yes, then how can it be done? I have only seen examples of applying inline css... ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the ...

Tips for including an external babel JS (ES6) file in an HTML document:

To include the babel js file in an HTML file, take a look at the code snippet below: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudfl ...

How can express.js be properly installed using typescript?

Currently, I am in the process of setting up a new project that involves using express.js with typescript integration. Would it suffice to just install @types/express by running the following command: npm install @types/express Alternatively, do I also ...

What is the best way to adjust a fixed-width table to completely fill the width of a smartphone browser?

In an ancient web application, the design was primarily constructed using rigid tables: <div class="main"> <table width="520" border="0" cellspacing="0" cellpadding="0"> <tr> <td>...</td> </ ...

Axios - Error: Promise Rejected - The request was unsuccessful with a 500 status code

The Axios post request in my code for adding new articles is not going through, and I am encountering an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Requ ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Issue with displaying options in Angular2 v2.4.9 HTML select element

Ever since I made the transition from AngularJS to Angular2, I've been facing a peculiar issue. The select element's options data is fetched from a Solr query, which always returns a 200 response with the data in a timely manner. However, the pr ...