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

Vue.js - Using parent data in component(Vue.js - 在组件中使用父数据)

本文介绍了Vue.js - 在组件中使用父数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

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

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" />                
</template>

Option 2

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

Parent

<template>
    <post :limit="limitByNumber" />
</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>
export default {
    props: ['list', 'limit'],

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

这篇关于Vue.js - 在组件中使用父数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Vue.js - 在组件中使用父数据

基础教程推荐