Child 组件中的 Vue 道具

Vue Props in Child component

我有两个组件,一个是 Parent 是一些随机页面,children 是一个将使用的组件,更多组件用于网格。

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>

最终看起来类似于:

使用分页换页时;有效但是,向我发送此错误:

我读到这个问题是指 "props in Vue is an anti-pattern"。

那么,如何解决?

最简单的解决方案是使用 b-pagination 的 @input 事件将更改后的值从子项发送到父项:

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

在方法中:

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

然后,在 parent 中,您必须通过将修饰符 .sync 应用于 prop 来接受更改的值,因此它还将处理 @update 事件:

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

注意:还要注意模板中道具的命名约定。 template 中的 props 建议使用 kebab-case,在 Javascript 中访问相同的 属性 驼峰式。