Tuuchen
Tuuchen

Reputation: 97

Vue.js passing data between components

I want to store input-value from App.vue, and use it in another component. How can I do it? I don't need the show the value in the template, I just need the value inside other components function. In JS I could just use a global var, but how can I achieve it 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 the basic logic I'm trying to achieve. Input value in App.vue --> anotherComponent.vue

Upvotes: 1

Views: 1461

Answers (1)

Konrad Słotwiński
Konrad Słotwiński

Reputation: 699

If components are not parent and child you can use store for this:

  1. More advanced vuex store that should be your default GO TO - NPM.

  2. Or simple solution with js object.

    a. Create store.js file and export object with property in which you will store value.

    b. Import store.js object to vue scripts and use it simply like:

import Store from 'store.js'

Store.value

Upvotes: 1

Related Questions