Manipulating all components of a specific type in App.vue with VueJS: Is it possible?

Consider this template with FruitPrices as a component:

<template>
  <div id="app">
    <div>
      <span @click=SOME_FUNCTION> Change currency </span>
      <FruitPrices fruit="apple"></FruitPrices>
      <FruitPrices fruit="banana"></FruitPrices>
      <FruitPrices fruit="orange"></FruitPrices>
             ...
             ....
             .....
</template>
...
...
...
import FruitPrices from ./component/FruitPrices.vue

Is it possible to create a method like SOME_FUNCTION that changes the currency for all instances of the FruitPrices Component in the main App? For example, changing components from USD or GBP to Euros using a method within the main app.

Answer №1

To ensure consistency across all components, consider storing the currency type in a property within the data object and create a function to update it as needed.

data() {
  return {
    currencyType: "USD",
    ...
  }
},
methods: {
  updateCurrency(newCurrency){
    this.currencyType = newCurrency;
  }
}

In your template, you can use:

<span @click=updateCurrency('Euro')> Change currency </span>

Answer №2

Utilizing this particular component allows for the seamless transfer of currency, price, and fruit information to each FruitPrices component:

<template>
  <div>
    <!-- By default, USD is selected. Any changes in options will automatically update prices -->
    <select v-model="currency">
      <option
        v-for="(currencyOption, index) in currencies"
        :key="index"
        :value="currencyOption"
      >
        {{ currencyOption.name }}
      </option>
    </select>
    <div v-for="(fruit, fruitIndex) in fruitsWithPrices" :key="fruitIndex">
      <FruitPrices :name="fruit.name" :convertedPrice="fruit.convertedPrice" />
    </div>
  </div>
</template>
<script>
import FruitPrices from '../somePlace/FruitPrices'
export default {
  name: "FruitPricesContainer",
  components: { FruitPrices },
  data: () => ({
    fruits: [
      {
        name: 'Apple',
        price: 0.2
      },
      {
        name: 'Banana',
        price: 0.3
      },
      {
        name: 'Orange',
        price: 0.25
      }
    ],
    currency: {
      exchangeRate: 1,
      name: 'USD'
    },
    currencies: [
      {
        exchangeRate: 1,
        name: 'USD'
      },
      {
        exchangeRate: 1.2,
        name: 'EUR'
      },
      {
        exchangeRate: 0.7,
        name: 'SGD'
      },
      {
        exchangeRate: 700,
        name: 'MXN'
      },
      {
        exchangeRate: 3700,
        name: 'COP'
      }
    ]
  }),
  computed: {
    fruitsWithPrices() {
      return this.fruits.map((fruit) => {
        return {
          ...fruit,
          convertedPrice: fruit.price * this.currency.exchangeRate
        }
      })
    }
  }
}
</script>

To complete the process, let's create the FruitPrices component:

<template>
  <div>
    <p>{{ name }}: {{ convertedPrice }}</p>
  </div>
</template>
<script>
export default {
  name: "FruitPrices",
  props: {
    name: {
      type: String,
      required: true
    },
    convertedPrice: {
      type: Number,
      required: true
    }
  }
}
</script>

The setup is complete! (Note: Not tested, please report any errors or issues).

Answer №3

Perhaps I haven't grasped the essence of your issue, but you could potentially leverage Vue's props in the following manner:

      <FruitPrices fruit="apple" :currency="newCurrency || 'USD'"></FruitPrices>
      <FruitPrices fruit="banana" :currency="newCurrency || 'GBP'"></FruitPrices>
      <FruitPrices fruit="orange" :currency="newCurrency || 'USD'"></FruitPrices>

You can declare the props currency within the FruitPrices component. In case the currency prop is unspecified, the second currency will serve as the default (e.g., "newCurrency || 'GBP'" where if newCurrency is null, GBP will act as the default currency).

For more information on Vue props, refer to: https://v2.vuejs.org/v2/guide/components-props.html

Subsequently, within the main template component, define the variable newCurrency and pass that variable to the currency prop of the FruitPrices component:

data: () => {
    newCurrency: null
},
methods: {
    setNewCurrency() {
        this.newCurrency = this.someFieldOfYourForm;
    }
}

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 with click function not activating in Chrome when using Angular 6

I am facing an issue where the (click) function is not triggering in my select tag when I use Google Chrome, but it works fine in Mozilla. Below is my code: <div class="col-xl-4 col-lg-9"> <select formControlName="deptId" class="form-control ...

The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer do ...

Trouble with CSS full height implementation within a scrolling container

I have been grappling with this straightforward issue for quite some time now. It seems to be a unique problem as I couldn't uncover a similar one online. My goal is to set the height of the green bar to 100% (to match the height of the red parent el ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

Automated Copy and Paste Feature - JavaScript using Ajax

I am working on a unique auto-increment IMDB ID grabber that retrieves the ID as you type the name of a TV show. Currently, I have managed to create functionality where it checks if the field is empty; if not, it displays a button that directs you to a pag ...

How can I use JQuery to iterate through Object data and dynamically create tr and td elements?

In previous projects, I utilized Vanilla JS to iterate through Ajax return data and construct tables. However, for this current project, I have decided to switch over to JQuery. The main reason behind this decision is that some of the td elements require s ...

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

Storing binary data uploaded via AJAX in PHP on the server is essential for maintaining

I successfully imported a .png image file as an Array Buffer. var readSingleFile = function(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); ...

Automatically populate input fields with text based on the option chosen from a dropdown menu

Having some issues here... I want to automatically populate the text input boxes in my form when a username is selected from the dropdown. The user data array is retrieved from a MySQL database. Not sure if my JavaScript code is correct. Here's my arr ...

Guide on transferring datetime information from a popup dialog to an MVC controller

My goal is to create a button that, when clicked, opens a dialog allowing the selection of start and end dates. Upon clicking ok/submit, the selected datetime should be passed to a controller [HttpPost] action method. Here's what I have attempted so f ...

"Learn how to compile a single jade file using grunt-jade instead of compiling all files at once

In my jade.js file, the code looks like this: 'use strict'; var config = require('../config'); module.exports = { dist: { options: { pretty: true, debug: false, timestamp: '<%= new Date().getTime() %>&apo ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

Transferring MongoDB information to a Jade template in an ExpressJS application

Hey there, hoping you can assist me with a query issue I'm facing. To give you some context, I am querying a MongoDB collection and trying to pass the results back to a Jade view. app.helpers({ clients: function(){ users.find({uid:req.session.u ...

Using inline styles can cause Content Security Policy (CSP) violations in applications

I have been diligently working on an application for quite some time using create-react-app. Recently, I decided to update to the latest version of React only to find out that a new Content Security Policy (CSP) has been implemented. To my dismay, upon tr ...

Building vue js logic to manage state across multiple ul li elements

I have a situation where I have an unordered list with a static number of list items (menu elements) that are rendered on the server side. I need to add some state-based logic to each list item, such as changing the color of the active item and expanding ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

How Can You Create a Sliding List Animation (Up/Down) Using Angular and Twitter-Bootstrap?

Hey, can you give me a hand with this? :) I'm attempting to create a sleek sliding up and down list in Angular, but I'm struggling to make it work. My CSS skills are not very advanced, so I'm still learning and gave it my best shot: http:// ...

Generate Swagger documentation for an API developed using Express 4.x

My challenge lies in documenting my Node and Express 4 server with Swagger for a client. I have explored various tools for this purpose, but haven't found the perfect fit yet. The swagger-node-express tool seems promising, but unfortunately does not ...

Determine browser compatibility by evaluating the DOM Level

Can we easily determine which browser versions and above are compatible with a certain DOM level? ...