简体   繁体   English

Vue.js - 在组件中使用父数据

[英]Vue.js - Using parent data in component

How I can get access to parent's data variable (limitByNumber) in my child component Post? 如何在我的子组件Post中访问父数据变量(limitByNumber)?

I tried to use prop but it doesn't work. 我试图使用道具,但它不起作用。

Parent: 家长:

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

new Vue ({
    el: 'body',

    components: { Post },

    data: {
        limitByNumber: 4
    }
});

Component Post: 组件发布:

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

Option 1 选项1

Use this.$parent.limitByNumber from child component. 使用this.$parent.limitByNumber来自子组件的this.$parent.limitByNumber 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 选项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>

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). 然后添加一些功能(如果你需要在所有组件中,可能会像vue.prototype或Mixin)。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM