Vue.js:从“父”Vue 获取数据

新手上路,请多包涵

我有一个(不可更改的)DOM 结构,如下所示:

 <div id="indexVue">
  ...
  <div id="childVue">
  ...
  </div>
  ...
</div>

还有两个js文件:

index.js:

 var child = require('childVue');

module.exports = new Vue({
  el: '#indexVue',
  ...
});

childVue.js:

 module.exports = new Vue({
  el: '#childVue',
  methods: {
    something: function(){
      // Parent data needed here ...
    },
    ...
  }
});

如图所示,我需要 indexVue 中的 childVue 的数据。有没有办法将它传递给它?我试图将其传递给带有 (v-on="click: childFunction($data)") 的函数,但这仅(逻辑上)从 childVue 而不是从 indexVue 返回数据属性。

谷歌并没有真正提供帮助,因为 Vue 没有很好的文档记录。

真正的文件和 DOM 结构更大更复杂,但我的问题需要的只是这些文件。

此外,我不允许在这里使用 jQuery,这将使其成为几秒钟的任务。

原文由 Nico Sänger 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 461
2 个回答

潘泰利斯的回答不再正确。 Vue.js 移除了继承属性。

最好的方法是 通过属性传递数据;

 <div id="indexVue">
  <child-vue :some-data="someData"></child-vue>
</div>

index.js:

 module.exports = new Vue({
  el: '#indexVue',
  data: {
    someData: "parent's data"
  },
  components: {
    childVue: require('childVue')
  }
});

childVue.js:

 module.exports = {
  template: '<div>{{someData}}</div>',
  methods: {
    something: function(){
      // you can access the parent's data
      console.log(this.someData)
    }
  },
  props: ['some-data'] // kebab case here available as camelcase in template
};

请注意 props 中的属性 childVue.js 以及用于属性名称的大小写( camelCase vs kebab-case

原文由 gsouf 发布,翻译遵循 CC BY-SA 4.0 许可协议

您也可以通过 this.$parent.someData 访问它,以防您无法将其绑定到道具上:) 例如:

 data() {
 return {
  parentData: this.$parent.someData
 }
}

原文由 TITO 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题