Nico Sänger Nico Sänger - 18 days ago 6
Javascript Question

vue js: Get data from "parent" vue

I have a (unchangeable) DOM-structure as followed:

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


And two js files:

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 ...
},
...
}
});


As shown, I need the data of the indexVue in childVue. Is there anyway to pass it to it? I tried to pass it to a function with (v-on="click: childFunction($data)"), but that only (logically) returns the data attribute from the childVue and not from the indexVue.

I am sure there is a simple way to do this, but I am to unexperienced with vue to see it. Google does not really help, as vue is not well documented.

The real file and dom structure is way bigger and complicated, but necessary for my problem are only these files.

Also I am not allowed to use jQuery here, which would make it a task of seconds ...

Answer

I suggest to use a child component to inherit the scope of its parent.

index.html

<div id="indexVue">
  <child-vue></child-vue>
</div>

index.js:

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

childVue.js:

module.exports = {
  inherit: true,
  template: '<div>...</div>',
  methods: {
    something: function(){
      // you can access the parent's data
      console.log(this.someData)
    }
  }
};
Comments