Vue.js passing data between components

孤人 提交于 2019-12-11 18:42:46

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/58765349/vue-js-passing-data-between-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!