【问题标题】:Vue - Passing same data from one component to many componentVue - 将相同的数据从一个组件传递到多个组件
【发布时间】:2017-09-02 07:49:17
【问题描述】:

我有以下代码。

ma​​in.js

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

App.vue

<template>
  <div id="app">
    // this does not pass the data to the component
    <basics :resume="resume"></basics>
    <education :resume="resume"></education>
    // this gets the value from the json file
    {{resumeData.name}}
    {{resumeData.education}}
  </div>
</template>

<script>

import Basics from './components/Basics.vue'
import Education from './components/Education.vue'
import Resume from '../resume.json'

export default {
  name: 'app',
  data() {
    return {
      resumeData: Resume
    }
  },
  components: {
    Basics,
    Education
  }
}
</script>

/components/Basics.vue

<template>
    <div>
        <p>Basics</p>
        // this does not get the value from the json file
        {{resumeData.name}}
    </div>
</template>

/components/Education.vue

<template>
    <div>
        <p>Education</p>
        {{resumeData.education}}
    </div>
</template>

如何将数据从一个组件传递到另一个组件,以便所有不同的 vue 组件都从同一个 json 文件中读取数据,而不在每个组件中插入代码 import Resume from '../resume.json

希望你能理解我的问题。

【问题讨论】:

    标签: javascript webpack vue.js vuejs2 vue-component


    【解决方案1】:

    更常见/标准的方式是使用道具。或者您必须在所有组件中导入 json。

    如果你有很多个组件并且真的不想多次传递同一个props,有一个棘手的解决方案:将数据全局注入到Vue.prototype:

    Vue.prototype.$resume = {
      name: 'foo',
      education: 'bar',
      ...
    }
    

    这样,您的所有组件都可以通过this.$resume 访问它。但要明智地使用它。

    如果你有其他类似的情况,你可能应该去vuex

    【讨论】:

      【解决方案2】:

      在 vue.js 课程中,您可以通过 3 种不同的方式解决这个问题。

      1. 在基础和教育中使用 props 传递数据
      2. Vuex
      3. 事件框

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-14
        • 2019-02-20
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        • 2019-07-12
        相关资源
        最近更新 更多