Component in Vue that dynamically updates text based on a given data value

This is the data I get and I what to be able to replace the data content with readable text:

From parent:

 data: [
    { name: 'discounts_offers', type: 'EMAIL', consent: true },
    { name: 'newsletter', type: 'EMAIL', consent: true },
    { name: 'product_upgrade', type: 'EMAIL', consent: true },
    { name: 'sms_offer', type: 'SMS', consent: true },
    { name: 'post_offer', type: 'POST', consent: true }
  ]

This is my included component

  <CommunicationPreference
    v-for="(communication, index) in data"
    :key="index"
    :communication="communication"
  />

Then the communicationPreference.vue:

<template>
  <section>
    {{ communication.name }} //This should be Newsletters etc
  </section>
</template>

<script>
export default {
  props: {
    communication: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {}
  },
  computed: {},
}
</script>

Then what I would like to do is if {{ communication.name }} equals 'discounts_offers' to use the text "Discounts and offers" like the images attached. Any solutions for the best approach to this?

https://i.sstatic.net/aPwJI.png

Answer №1

To handle scenarios like this, you can utilize computed properties. Here is an example:

App.vue

<template>
  <CommunicationPreference
    v-for="(communication, index) in preferences"
    :key="index"
    :type="communication.type"
    :name="communication.name"
    v-model:consent="preferences[index].consent"
  />
</template>

<script>
import CommunicationPreference from "./components/CommunicationPreference.vue";

export default {
  name: "App",
  components: {
    CommunicationPreference,
  },
  data() {
    return {
      preferences: [
        { name: "discounts_offers", type: "EMAIL", consent: true },
        { name: "newsletter", type: "EMAIL", consent: true },
        { name: "product_upgrade", type: "EMAIL", consent: true },
        { name: "sms_offer", type: "SMS", consent: true },
        { name: "post_offer", type: "POST", consent: true },
      ],
    };
  },
};
</script>

and in CommunicationPreference.vue

<template>
  <div>
    <label
      ><input
        type="checkbox"
        name="preference"
        :value="consent"
        :checked="consent === true"
        @change="$emit('update:consent', $event.target.checked)"
      />{{ label }}</label
    >
  </div>
</template>

<script>
export default {
  name: "CommunicationPreference",
  props: {
    type: String,
    name: String,
    consent: Boolean,
  },
  computed: {
    label() {
      if (this.name === "newsletter") {
        return "Newsletters";
      }

      if (this.name === "discounts_offers") {
        return "Discount and offers";
      }

      if (this.name === "product_upgrade") {
        return "Upgrade recommendations";
      }

      return this.name;
    },
  },
};
</script>

This code snippet provides a general idea of how to approach the issue, but it has not been tested.

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

What is preventing my Three.js object from responding to my commands to move?

I'm currently working on a three.js project where I want to create a block that moves when different keys are pressed. I've managed to set up a functional event listener, used console.log() for checking purposes, and successfully moved the block ...

As soon as I define a variable in my Vue Vite Tailwind project, my scss file seems to stop functioning properly

I encountered an issue in a vue project utilizing vite and tailwindcss. I decided to incorporate sass, so I performed the following steps: npm add -D sass Next, I created a main.scss file at the root of the project (vue folder). Within this file, I inclu ...

NodeJS JSON file write function not updating as expected

I'm working on a task that involves reading an existing JSON file, updating the value within it, and then saving it back. However, I've encountered the following error message: node:internal/modules/cjs/loader:944 throw err; ^ Error: Cannot ...

Integrating Whatsapp cloud API with a React web application allows for seamless communication between

I'm currently in the process of integrating my web application with the WhatsApp cloud API. While I've had success sending test messages, I am now looking to incorporate variables as outlined in the API documentation. However, I seem to be encoun ...

Expanding the fields in passport.js local strategy

Passport.js typically only allows for username and password in its middleware as default. I am looking to include a third field in Passport.js. Specifically, I require username, email, and password to be utilized in my case. ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

Vue.js is rendering the chart inaccurately in dc.js

I am currently facing an issue with using dc.js inside a Vue component. My linechart has this filled black area and the brush tool looks different from the normal brush tool. I took this code from my plain JavaScript project. <template> <div> ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

Is it possible to create a special case for the beforeunload function?

Is there a way to exclude a specific URL or form button from the beforeunload event in JavaScript? I want to exempt them, not as error handling exceptions but to customize how they interact with this event. Here is the relevant JavaScript code: if(loggedi ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

Tips for filling a Rails dropdown list using a JSON array

My Ant show page showcases detailed information about different types of ants. There are two drop downs on the page - one for environment: [indoor, outdoor], and another for diet: [sugar, fat, protein]. When a parameter is selected from each dropdown, it ...

Navigating the Abyss: Exploring Relationships and Updates in Django Rest Framework with Serializers and Many-to-Many Connections

I've been struggling with this issue for hours, but I just can't seem to find the solution. It's really starting to frustrate me. The problem I'm facing is that I have a parent model with multiple children associated with it. I've ...

Modify the properties of the following bdi element that contains text using JQuery

I am not a tech expert, but I have created a script and am running it on a website using Tampermonkey. Website code:- <div id="__grid1-wrapperfor-__label44" class="sapUiRespGridSpanL1 sapUiRespGridSpanM3 sapUiRespGridSpanS6 sapUiRespGridS ...

Is there a way to locate the source or URL linked to a button on a form or webpage?

Currently, I am extracting data feeds from a webpage by clicking a button that is similar to the 'Login' button displayed on the following link: However, this button acts as a 'Download' request that initiates the download of a csv rep ...

Problem with displaying legends in a stacked bar chart using jqplot

I am encountering a problem with the legend placement on the jqplot stacked bar chart. I want to customize the positioning of the legend, but my changes are not taking effect. What I desire is this: However, what I am currently seeing in the legend is as ...

Prevent sluggish script performance using GreaseMonkey

When I go to a certain website, there is an external script that loads very slowly, causing the page to be almost unusable at times. While disabling the script helps a bit, it means losing out on some important functionality. I'm wondering if there i ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

5 Bootstrap Popovers with Custom HTML Contents

I am having trouble separating the content of the bootstrap5 popover from the HTML attributes, unlike other components where it is achievable. var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]')) var ...

Issue encountered while retrieving values from JSON for the data table

I recently developed an application using a combination of React and Flask to display JSON data in a table format. While I can successfully see the data loaded in the console, I encountered difficulties in rendering it within the data table. The technologi ...

deleting the selected list item with JavaScript

Currently, I am tackling a todo list project but facing a challenge in finding a vanilla Javascript solution to remove a list item once it has been clicked. Adding user input as list items was relatively simple, but I have come to realize that this specif ...