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

Vue.js - Using parent data in component

如何在我的子组件中访问父级的数据变量 (limitByNumber) Post?

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

家长:

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

new Vue ({
    el: 'body',

    components: { Post },

    data: {
        limitByNumber: 4
    }
});

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

选项 1

使用 child 组件中的 this.$parent.limitByNumber。所以你的组件模板应该是这样的

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

选项 2

想用道具,也能达到你想要的效果。像这样。

Parent

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

Child 花盆

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

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

    created() {
        this.list = JSON.parse(this.list);
    }
}
</script>

如果你想访问某个特定的父级,你可以这样命名所有组件:

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