简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM