Revamp the Vue component for better DRYness

Seeking advice on a more efficient way to improve the code below and make it DRY:

<h2>{{ title }}</h2>
<p>{{ subtitle }}</p>

I am currently checking this.name for both the title and subtitle, wondering if there is a better implementation than what I have. Any suggestions?

computed: {
    title() {
        switch (this.name) {
            case 'discounts_offers':
                return this.$t('discounts.title');
            case 'newsletter':
                return this.$t('newsletters.title');
            case 'product_upgrade':
                return this.$t('upgrade.title');
            default:
                return this.name;
        }
    },
    subtitle() {
        switch (this.name) {
            case 'discounts_offers':
                return this.$t('discounts.subtitle');
            case 'newsletter':
                return this.$t('newsletters.subtitle');
            case 'product_upgrade':
                return this.$t('upgrade.subtitle');
            default:
                return this.name;
        }
    },
}

Answer №1

Here's what I propose:

The keys in the literal should match the value stored in this.name. This way, you can easily translate them on-the-fly.

Instead of using multiple if/else statements, you can achieve the same with just one line of code.

displayTitle() {
  return this.$t(this.name)
}

Answer №2

Could you try something along these lines?

data() {
    return {
      map: {
        discounts_offers: "discounts",
        newsletter: "newsletters",
        product_upgrade: "upgrade"
      }
    }
  },
  computed: {
    title() {
      return this.map[this.name] ? this.$t(`${this.map[this.name]}.title`) : this.name
    },
    subtitle() {
      return this.map[this.name] ? this.$t(`${this.map[this.name]}.subtitle`) : this.name
    },
  }

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

Transforming Arrays of Objects into a Single Object (Using ES6 Syntax)

My attempt to create aesthetically pleasing Objects of arrays resulted in something unexpected. { "label": [ "Instagram" ], "value": [ "@username" ] } How can I transform it into the d ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

Is it possible to alter the link color in vuetify components without modifying the primary color?

Is there a way to change the link color in Vuetify without altering the primary theme color? $material-light: ( "background": $telenor-color-background, "text": ( "link": red, ), ); Unfortunately, this approach did ...

Execute the command "prisma migrate dev" to update the existing database

I'm currently in the process of configuring Prisma migrate on a pre-populated MySQL database in my development environment, but I'm facing challenges getting it to function correctly. 1. After executing prisma db pull successfully to generate th ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. https://i.sstatic.net/DAb1q.png Referring to the image provided, the first 'Produ ...

Micro Frontend: Implementing a Pubsub System for Scalable Front-End Architecture

Currently, I am developing a large-scale application using the innovative micro front end architecture. The application is split into 5 Micro Apps: (micro-app-A (developed in Vue), micro-app-B (built with Vue), micro-app-C (using Angular), micro-app-D (cre ...

How come setting an optionsValue causes Knockout updating to malfunction?

As I delved into the Knockout tutorials, one particular tutorial caught my attention. Here is the HTML snippet that puzzled me: <h2>Your seat reservations</h2> <table> <thead><tr> <th>Passenger name</th& ...

Using both the variable and the JSON format from the Google Maps API

I am trying to display the coordinates from the input fields on a map using Google Maps API. However, I am facing an issue with passing the values to the script. Below is the code snippet: <input type="text" id="latitude" class="form-control" /> ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

The React page is stuck in a perpetual cycle of reloading every single second

After developing an invoice dashboard system using React, I encountered a recurring issue with a similar version of the app built on React. Even after commenting out all API calls, the useEffect(), the page kept reloading every second. Any advice or sugge ...

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

Is there a way to handle templates in AngularJS that is reminiscent of Handlebars?

Is there a way to handle an AngularJS template using a syntax similar to Handlebar? <script type="text/ng-template" id="mytemplate"> Name is {{name}} </script> I know how to retrieve the template using $templateCache.get('mytemplate&ap ...

Express fails to pass password validation

I encountered an issue with a ValidationError stating that the Path password is required while attempting to register a new User. My experience in Node, programming, and authentication is limited. Below is the code for the User model and schema where I ma ...

Navigate post Ajax call

When I make an unauthenticated GET request using AJAX, my server is supposed to redirect my application. However, when I receive the redirect (a 303 with /login.html as the location), the response tab in the Firebug console shows me the full HTML of the lo ...

Canceling text as soon as the search input is entered in Vue.js

When I use the search input box, the last text I typed in gets cancelled. Can anyone help me with this issue? <input class="navbar-searchbar__text-field" type="search" :value="searchQuery" name=" ...

Error: The value property is undefined and cannot be read at the HTMLButtonElement

I'm currently working on a project where I need to display a dropdown menu of buttons using Pug in order to render an HTML page. To achieve this, I am using the getElementsByClassName('dropdown-item') method to retrieve all the buttons in an ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

Is there a way to bypass the final function call when using Express Middleware?

In my Node.js project using express, I have a function inside a get route... The function currently includes a simple caching functionality that I coded myself. It queries data from an MSSQL Database and returns it using res.json(data). However, I want to ...

Variable in Javascript file causing return value to be 'undefined'

I have encountered an issue with my JavaScript file. It is extracting data from a SharePoint list and displaying it on an HTML page, but one of the fields appears as 'undefined' even though I defined it initially. The problematic variable is &ap ...