Vue.js - using parent data in a component

How can I access the parent data variable (limitByNumber) in my Post child component?

I tried using prop, but it does not work.

Parent:

import Post from './components/Post.vue';

new Vue ({
    el: 'body',

    components: { Post },

    data: {
        limitByNumber: 4
    }
});

Component Message:

<template>
            <div class="Post" v-for="post in list | limitBy limitByNumber">
                <!-- Blog Post -->
....
</div>
</template>


<!-- script -->    
<script>
        export default {
            props: ['list', 'limitByNumber'],


            created() {
                this.list = JSON.parse(this.list);
            }

        }
</script>
+16
source share
2 answers

Option 1

Use this.$parent.limitByNumberfrom a child component. So your component template will be this way

<template>
    <div class="Post" v-for="post in list | limitBy this.$parent.limitByNumber">                
    </div>
</template>

Option 2

If you want to use props, you can also achieve what you want. Like this.

Parent

<template>
   <post :limit="limitByNumber"></post>
</template>
<script>
export default {
    data () {
        return {
            limitByNumber: 4
        }
    }
}
</script>

Baby pots

<template>
            <div class="Post" v-for="post in list | limitBy limit">
                <!-- Blog Post -->
....
</div>
</template>


<!-- script -->    
<script>
        export default {
            props: ['list', 'limit'],


            created() {
                this.list = JSON.parse(this.list);
            }

        }
</script>
+41
source

If you want to access a specific parent, you can name all components as follows:

export default {
  name: 'LayoutDefault'

(, vue.prototype Mixin, ). :

getParent(name){
      let p = this.$parent;
      while(typeof p !== 'undefined'){
        if(p.$options.name == name) {
          return p;
        }else {
          p = p.$parent;
        }
      }
      return false;
    }

:

this.getParent('LayoutDefault').myVariableOrMethod
0

All Articles