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

It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it. This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I beli ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

Enhance your Morris.js charts by incorporating detailed notes and annotations

Is there a way to include annotations in my morris.js charts? I couldn't find any information about this on their official website. I specifically need to add notes to certain dates. ...

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

When the state inspection fails due to a missing object property, the function will not work as intended

I'm currently in the process of developing a weather app. The user will input either a zip code or a city name + state, triggering the $.getJSON function to gather data. One key feature I am working on involves checking if the user's input is va ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

Retrieve a JSON file from the local file system using AngularJS

I recently started learning AngularJS and I am trying to read a JSON file from my local system. However, when I attempt to do so, I encounter an exception error that says: "Access to restricted URI denied XMLHttpRequest." Here is the code snippet: var de ...

What should I do to resolve the message 'Ignoring invalid configuration option passed to Connection' that I received?

This is the latest message: Warning - Invalid configuration option passed to Connection: createDatabaseTable. Currently a warning, future versions of MySQL2 will throw an error for passing invalid options. The application stops responding after enco ...

Make sure to declare any reactive properties in the data option when creating a Vue instance, instead of adding them at runtime to the root $data. By doing

I am facing some confusion while working with VueJS2. I included a few variables in the data container to send them to my API successfully. However, Vue is displaying a warning/error message that I am unsure how to resolve: It is recommended to avoid ...

Having trouble unselecting the previous item when selecting a new item in Reactjs

I have a list of items and I want to change the background color of the currently selected item only. The previously selected item should deselect. However, at the moment, all items are changing when I click on each one. Can anyone help me solve this issue ...

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

Using Vue.js for instant field validation when sending PHP post forms for enhanced user experience

A unique approach is being taken to utilize vue.js exclusively for real-time field validation, while the form will ultimately be submitted using PHP through the POST method. However, a challenge arises where vue.js takes control of the form, hindering PHP& ...

Looking to create a GitHub example in Fiddle but running into issues with getting the result?

I've been working on an example on Fiddle, but it's not functioning as expected. I want to implement i18next so that the text changes when the user switches languages. After searching for a solution, I came across this GitHub repository: https:// ...

"Enhance your networking capabilities with a Node.js HTTP proxy featuring a dynamic proxy

I'm attempting to make websockets function properly with node-http-proxy. The unique aspect is that I am using a proxy table configuration: var options = { router: { 'a.websterten.com': '127.0.0.1:150', 'b.websterten. ...

Looking for a solution to the problem: Module 'import-local' not found

internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'import-local' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modules/cjs/loader.js:520:25) Encoun ...

Is it possible to pass a prop down through 2 levels of nested children components?

I am facing an issue with passing a prop in my component. The id is passed as a prop like this: <comments myId="1"></comments> In the comments component, I have defined the prop like this: props: [ 'myId', ], Within the commen ...

Issues with FUNCTION_INVOCATION_FAILED error encountered during deployment on Vercel and Nuxt

Just imported a Nuxt project from GitHub that includes the vercel.json config: { "version": 2, "builds": [ { "src": "nuxt.config.js", "use": "@nuxtjs/vercel-builder" ...