Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Using parent data in component

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> 
like image 594
Michał Lipa Avatar asked Apr 19 '16 14:04

Michał Lipa


People also ask

How do you access data from parent component Vue?

To access child component's data from parent with Vue. js, we can assign a ref to the child component. And then we can access the child component data as a property of the ref. to assign the markdown ref to the markdown component.

How do I transfer data from component to component in Vue?

VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


2 Answers

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> 
like image 82
Yerko Palma Avatar answered Sep 29 '22 11:09

Yerko Palma


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 
like image 43
Catch Avatar answered Sep 29 '22 13:09

Catch