Vue.js - Using parent data in component

后端 未结 2 1306
傲寒
傲寒 2020-12-28 12:02

How I can get access to parent\'s data variable (limitByNumber) in my child component Post?

I tried to use prop but it doesn\'t work.

Parent:

相关标签:
2条回答
  • 2020-12-28 12:18

    If you want to access some specific parent, you can name all components like this:

    export default {
      name: 'LayoutDefault'
    

    And then add some function (maybe like vue.prototype or Mixin if you need it in all your components). Something like this should do it:

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

    and usage could be like this:

    this.getParent('LayoutDefault').myVariableOrMethod
    
    0 讨论(0)
  • Option 1

    Use this.$parent.limitByNumber from child component. So your Component template would be like this

    <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>
    

    Child 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>
    
    0 讨论(0)
提交回复
热议问题