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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36722170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:28:56  来源:igfitidea点击:

Vue.js - Using parent data in component

javascriptvue.jsvue-component

提问by Micha? Lipa

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.

我尝试使用 prop 但它不起作用。

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>

回答by Yerko Palma

Option 1

选项1

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

this.$parent.limitByNumber从子组件使用。所以你的组件模板会是这样的

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

回答by Catch

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:

然后添加一些函数(如果你的所有组件都需要它,可能像 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;
    }

and usage could be like this:

和用法可能是这样的:

this.getParent('LayoutDefault').myVariableOrMethod