carlos-silva
carlos-silva

Reputation: 95

Vue Props in Child component

I have two components one is a Parent is some page random, and children is a component will use and more components for grids.

Parent

<template>
...
  <DataTable
   :items="items"
   :fields="fields"
   :currentPage="currentPage"
   :perPage="perPage"
   :filter="filter"
   :sortBy="sortBy"
   :sortDesc="sortDesc"
   :sortDirection="sortDirection">
  </DataTable>
...
</template>

<script>
 import DataTable from "./DataTable.vue";

 components: {
  DataTable,        
 },
 data: function(){
  return {
   fields: [],
   items: [],
   currentPage: 1,
   perPage: 2,
   filter: null,
   sortBy: null,
   sortDesc: false,
   sortDirection: 'asc',
  }
 }
</script>

Child

<template>
...
  <b-table 
   show-empty
   stacked="md"
   :items="items"
   :fields="fields"
   :current-page="currentPage"
   :per-page="perPage"
   :filter="filter"
   :sort-by="sortBy"
   :sort-desc="sortDesc"
   :sort-direction="sortDirection">
  </b-table>
  <b-row>
   <b-col md="6" class="my-1">
    <b-pagination 
     :total-rows="items.length" 
     :per-page="perPage" 
     v-model="currentPageComputed"
     class="my-0" />
   </b-col>
  </b-row>
...
</template>

<script>
 props: {
  items: Array,
  fields: Array,
  currentPage: Number,
  perPage: Number,
  filter: String,
  sortBy: String,
  sortDesc: Boolean,
  sortDirection: String,
 },
 computed: {
  currentPageComputed: {
   get () {
    return this.$props.currentPage
   },
   set (i) {
    this.$props.currentPage = i;
   }
  },    
 },
</script>

Finally looks similar to: Visual

when use the pagination for change of page; works But, send me this error:

Error by devtools

I read this problem is referent to "props in Vue is an anti-pattern".

So, how a fix?

Upvotes: 1

Views: 783

Answers (1)

Igor Moraru
Igor Moraru

Reputation: 7729

The simplest solution is to to use the @input event of b-pagination to emit the changed value from child to parent:

<b-pagination 
     :total-rows="items.length" 
     :per-page="perPage" 
     :value="currentPage"
     @input='emitPageValue'
     class="my-0" />
   </b-col>

And in methods:

methods: {
 emitPageValue(value){
   this.$emit('update:current-page', value)
 }
}

Then, in parent you have to accept the changed value by applying the modifier .sync to the prop, so it will also handle the @update event:

<template>
...
  <DataTable
   :items="items"
   :fields="fields"
   :current-page.sync="currentPage"
   :per-page="perPage"
   :filter="filter"
   :sort-by="sortBy"
   :sort-desc="sortDesc"
   :sort-direction="sortDirection">
  </DataTable>
...
</template>

NB: Also pay attention to naming convention for props in template. It is recommended to use kebab-case for props in template and access the same property in camelCase in Javascript.

Upvotes: 3

Related Questions