Sharing information between Vue.js components

I need to store the input value from App.vue and utilize it in another component without displaying it in the template. In JavaScript, I could use a global variable, but how can I accomplish this in Vue?

App.vue:

<template>
  <div id='app'>
    <!-- App.vue has search bar -->
    <b-form-input @keydown='search' v-model='input'></b-form-input>
    <div>
      <!-- Here's my other components -->
      <router-view />
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      input: '',
      value: ''
    }
  },
  methods: {
    search () {
      this.value = this.input
      this.input = ''
    }
  }
}
</script>

Another component:

<template>
  <div>
    <p>I'm another component</p>
    <p>App.vue input value was: {{value}} </p>
  </div>
</template>

<script>
export default {
  props: ['value'],
  data () {
    return {
      value: ''
    }
  }
}
</script>

This is how I am planning to achieve the desired functionality: Capturing the input value in App.vue and transferring it to anotherComponent.vue.

Answer №1

In cases where components are not directly related as parent and child, utilizing a store can be beneficial:

  1. Utilize a more advanced vuex store as your primary option - Visit NPM for more information.

  2. Alternatively, opt for a simple solution using a JavaScript object.

    a. Begin by creating a file named store.js, and export an object with the necessary property to store the value.

    b. Next, import the store.js object into your Vue scripts, and use it like so:

import Store from 'store.js'

Store.value

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

Develop a reusable method/function within a JavaScript class for future use

I encountered an error message stating React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. I am trying to create a public method within a class so that I ca ...

jQuery parseFloat causing loss of precision in price values

The code extracts a price value from a hidden input field named '#orginalAddon', then adds the cost of additional addons to this value and displays the total amount to the user. However, there seems to be an issue with truncation when the value i ...

The Promise instantiated using Promise.reject() is executed instantly

While running the program below const somePromise = Promise.reject("Shouldn't see this"); function f1() { console.log("Hello World"); } f1(); The output displayed is as follows: Hello World (node:23636) UnhandledPromiseRejectionWarning: Shouldn& ...

Iterate through the elements of an array and showcase only those that meet a specific condition, all

I am working with a state in Pinia that consists of an array of objects. I populate this array by fetching data, which I then display in a component by using v-for to iterate through the elements and show them as cards. In the parent component where I mana ...

Unable to transfer data from one array to another array

I need to transfer data from one array to another in order to manipulate it. Here is the code: let data=[]; this.dataArray.length=0; this.dataArray=[]; for(var i=0;i<this.test.length;i++){ data.push(this.test[i]); } data.forEach((element)=>{ let ...

ag-grid: Enable row dragging by allowing users to drag the entire row

Currently, I am utilizing the Vue version of ag-grid 21.2.1 (https://www.ag-grid.com/vue-getting-started/) and successfully integrated Row Dragging (https://www.ag-grid.com/javascript-grid-row-dragging/) feature on one of our tables. Everything is function ...

Is there a way to make Express.js pass parameters with special characters exactly as they are?

I am currently working on a project within the freeCodeCamp "API and Microservices" curriculum that involves using Express.js to handle routes. The project itself is relatively straightforward, with some pre-defined routes and others that need to be creat ...

Is there a way to modify the background color of ::before when hovering over it?

I have a ul-li list and when i hover last li ::before element looks white and not so good. I want to change it when i hover the last li element. How can I achieve this? Here are my codes: <div className="dropup-content"> <ul> & ...

Utilize the asynchronous module created by Caolan to retrieve a specific value

I am curious about whether it is feasible to use the async.each method to perform a series of calculations and retrieve the resulting value. For instance, one such scenario could involve calculating the sum of all elements in an array. function Calculator ...

Having difficulty in compressing Vue.js application

My Vue.js Application contains the following code snippet: (function() { initApp(); })(); function initApp() { window.myApp = new Vue({ el: '#wrapper', data() { return { somedata: [] } } }); } & ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Customize your Kendo AngularJS Date picker to display formatted date by setting ng-model from timestamp

Here is a date time picker I have set up based on the documentation provided at this link: <input kendo-date-picker k-options="monthSelectorOptions" ng-model="milestone.estimate" k-ng-model ...

jquery causing issues with browser functionality

I'm new to working with JQuery and currently in the process of deconstructing a code snippet I found online. The code functions perfectly fine on JSFiddle: JSFIDDLE. However, when attempting to run it in a browser, the section that should appear upon ...

Sharing an automator variable with javascript

Is there a way for me to access the selected text in my automator workflow? When using the "Run bash action", I have the convenient option of "pass input as arguments". However, with the "Run JavaScript" action, this isn't available. How can I effect ...

Are there any unique approaches to calculating PI through the use of lazy evaluation sequences?

Recently, I've been utilizing lazy.js in my JavaScript projects. One interesting question came to mind - is there a clever method to define PI using lazy evaluation, without actually calculating it? I understand that lazy evaluation is call-by-need, ...

Is there a way to use NPM jsdom to determine the number of text lines in an HTML document?

const jsdom = require("jsdom"); const { JSDOM } = jsdom; var htmlContent = "<p>line 1</p><p>another line</p><p>line 3</p><script>//not a line</script><p>last line</p>" let domParser = new JSDOM(ht ...

The website was accessed via HTTPS, but an insecure XMLHttpRequest endpoint from the same website was requested

My axios request below is going out over https, but I'm encountering a specific error: The page at 'http://websitename/folder1/folder2/api/atlas/home/coach' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http: ...

Display or conceal a text field in Vue 2/Vuetify 1.5 depending on whether a checkbox is selected, with the possibility of duplicated

I've created a product checkbox selection feature that dynamically shows or hides text fields based on the user's selection. Unfortunately, there is a glitch in the system where selecting the second item causes duplication of text fields from th ...

Guidelines for sending data to child components using Vue Router

I'm currently working on a Vue component that includes Navigation and layout features and relies on a bus to communicate with its sub-components. The bus is passed down as a prop to the sub components, which then utilize $emit for communication. expo ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...