...
...
...And...">

Vue js: Get data from parent vue

I have a (immutable) DOM structure:

<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 indexVue data in childVue. In any case, pass it on to him? I tried passing it to a function using (v-on = "click: childFunction ($ data)"), but only (logically) returns the data attribute from childVue, not from indexVue.

I'm sure there is an easy way to do this, but I have to be inexperienced with vue to see it. Google really doesn't help, as vue is not well documented.

The real structure of the file and dom is bigger and more complicated, but for my problem only these files are needed.

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

+4
3

child component inherit .

index.html

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

index.js:

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

childVue.js:

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

. Vue.js inherit.

- ;

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

index.js:

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

childVue.js:

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

props childVue.js (camelCase vs kebab-case),

+14

You can also access it. $ parent.someData in case you cannot bind it to the prop element :) for example:

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

Source: https://habr.com/ru/post/1606595/


All Articles