我有两个组成部分,一个是父项,某个页面是随机的,子项是一个将使用的组件,而更多的是网格组件。
父母
<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>
孩子
<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>
使用分页进行页面更改时;可以但是,将这个错误发送给我:
我读到此问题是指“ Vue中的props是反模式”。
那么,如何解决?
答案 0 :(得分:2)
最简单的解决方案是使用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)
}
}
然后,在父级中,您必须通过将修改器.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>
注意:也要注意模板中道具的命名约定。建议在模板中使用kebab-case作为道具,并在Javascript中使用camelCase访问相同的属性。