Looking to generate a computed attribute?

Trying to adjust the font size of text using a dropdown and so far it's working as expected. However, is there a more efficient way to achieve this, such as using a computed property or watcher? I'm not sure how to go about implementing that.

Here's a link to a pen that I've been working on: https://codepen.io/anon/pen/xoMXPB?editors=1011. How can I modify the logic on line 6 to incorporate a computed property or watcher?

<div id="app">
    <v-app id="inspire">
        <v-container>
            <v-select :items="items" label="Font-Size" v-model="myFont">
            </v-select>
            <div>
                <p :style="{'font-size': myFont == 'Large' ? 24 + 'px' : myFont == 
     'Medium' ? 18 + 'px' : 14 + 'px'}">Large="24px", Small="16px",
                    Medium="18px"</p>
            </div>
        </v-container>
    </v-app>
</div>


new Vue({
    el: '#app',
    data() {
        return {
            items: [
                'Large',
                'Medium',
                'Small',
            ],
            myFont: null,
        };
    },
})

Any assistance would be greatly appreciated.

Answer №1

If you were to consider using a computed property (or perhaps a method in this particular scenario), it could assist you in streamlining the code and improving its adaptability;

methods: {
  adjustTextSize: function(size){
   switch(size){
    case "LARGE":
      return "24px";
    case "MEDIUM":
      return "18px";
    default:
      return "14px";
   }
  }
}
<p :style="adjustTextSize(myFont)"></p>

Answer №2

Have you considered using an array of objects as options to simplify the conditional in the computed property?

Take note of the item-text and item-value props in the v-select. With this setup, the conditional can simply add the style syntax font-size: ${this.myFont}px

Vue.config.silent = true;
Vue.use(Vuetify);

new Vue({
  el: '#app',
  data: () => ({
    items: [
      { label: 'Large', value: 24 },
      { label: 'Medium', value: 18 },
      { label: 'Small', value: 16 },
    ],
    myFont: 16
  }),
  computed: {
    style() {
      return `font-size: ${this.myFont}px` ;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384e4d5d4c515e417809160d1609">[email protected]</a>/dist/vuetify.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b0b3a3b2afa0bf86f7e8f3e8f7f2">[email protected]</a>/dist/vuetify.min.css">

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-select :items="items" item-text="label" item-value="value" label="Font-Size" v-model="myFont"></v-select>
      <div>
        <p :style="style">Font is {{myFont}}px</p>
      </div>
    </v-container>
  </v-app>
</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

Exploring the process of acquiring a button using refs in external JavaScript

Having encountered a situation where I have two different javascript files, I came across an issue. The first file contains a finish button that was initialized by using refs. Now, I need to access this button in the second file using refs. The code snipp ...

Ways to prevent users from manually inputting dates in date fields

I am currently developing an application and I need to prevent users from manually entering a date in the type=date field on the HTML page. I want to restrict users to only be able to select a date from the calendar display, which is in the format MM/DD/YY ...

"Implementing an AngularJS factory that returns a State object instead of typical JSON data fetched from

I have created two factories and I am calling the first one from the second one in my controller. However, instead of receiving JSON data, I am getting data as $$State. I am new to AngularJS and have tried multiple solutions but have not been able to resol ...

Adding a half circle connector in HTML can be accomplished by using SVG (Scal

My task is to replicate the construction shown in this image: https://i.sstatic.net/kaRMO.png I have written the entire code but I am unsure how to include a half circle next to the full circle and connect it with a line connector. Here is my code: .ps- ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

Utilizing socket.io to access the session object in an express application

While utilizing socket.io with express and incorporating express session along with express-socket.io-session, I am encountering difficulty in accessing the properties of the express session within the socket.io session object, and vice versa. const serve ...

AngularJS, the element being referenced by the directive is empty

Currently, I am in the process of transferring a jQuery plugin to AngularJS simply for the enjoyment of it. Previously, when working with jQuery, my focus was on manipulating the DOM using jQuery functions within the plugin loading function. Now that I am ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

How come my donut graphs are sitting outside the box while all other types of charts are properly aligned?

I am encountering an issue with my charts where all of them are positioned in the center of a div when drawn by the user, except for the donut charts. They seem to be placed outside of the top-left corner instead. Can anyone provide insights as to why this ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

"Unraveling Loopback: The Ultimate Guide to Accessing Every Role Assigned to a

Currently, I am in the process of developing a Loopback application where I have customized a user model based on the pre-built User model. { "name": "user", "base": "User", "idInjection": true, "properties": { "test": { "type": "string" ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

Unable to receive data from jQuery AJAX request

I'm feeling a little puzzled at the moment. Whenever I run my ajax call, the error function is triggered every time. I am aware that the data is returning as JSON, and I have set the datatype as jsonp to enable cross-origin functionality. I am not sur ...

Simple way to extract the values from every input element within a specific <tr> tag using JQuery

Is there a way to align all input elements in a single row within my form? For example, consider the snippet of code provided below, which includes a checkbox and a text input box. I would like to retrieve the values from both of these input types and pres ...

It's next to impossible to secure expedited work on an ongoing project using Vercel

Yesterday, I successfully deployed an application on Vercel using only ReactJS. Today, I made the decision to develop an API for my application, To clarify, I have a folder housing the React app, and within that, I created a directory named "api" followi ...

JavaScript finding items in an array

The main issue I am encountering involves receiving a notification when the term (city name within the project) entered by the user in JqueryUI Autocomplete does not match anything in the collection (e.g. user entered "My Sweet City" and it does not matc ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...