"不要在突变处理程序之外改变 vuex 存储状态"错误,即使在对 prop 使用计算的 var 之后



使用以下组件,我收到Error: [vuex] do not mutate vuex store state outside mutation handlers.错误:

<template>
<div>
<v-data-table
:headers="headers"
:items="items"
:search="search"
:key="tableKey"
:pagination.sync="pagination"
disable-initial-sort
rowKey
>
<template slot="items" slot-scope="props">
<tr @click="clicked(props.item)" :class="{'secondary': props.item[rowKey]===selectedCode}">
<td v-for="header in headers" :key="header.value">
<BaseTableColumn
:item="props.item"
:index="header.value"
:format="header.format"
/>
</td>
</tr>
</template>
</v-data-table>
</div>
</template>
<script>
export default {
name: 'BaseTable',
props: {
headers: Array,
items: Array,
search: String,
tableKey: String,
rowKey: String,
},
data: () => ({
pagination: {
rowsPerPage: 10,
totalItems: -1,
},
selectedCode: -1,
}),
components: {
BaseTableColumn: () => import('@/components/base/BaseTableColumn'),
},
methods: {
clicked(row) {
window.scrollTo(0, 0);
this.selectedCode = row[this.rowKey];
this.$set(row, 'selected', true);
this.$emit('rowClick', row);
},
highlightFirst(items) {
this.selectedCode = this.items[0][this.rowKey];
this.$set(this.items[0], 'selected', true);
},
},
updated() {
if (this.selectedCode === -1 && (typeof this.items === 'object') && this.items.length > 0) {
this.highlightFirst(this.items);
}
},
};
</script>

作为参考,这里是headers.js

const headers = [
{
text: 'Tenant Code',
value: 'code',
},
{
text: 'Tenant ID',
value: 'name',
},
];
export default headers;

BaseTableColumn.vue

<script>
export default {
name: 'BaseTableColumn',
props: {
format: Function,
item: Object,
index: String,
},
methods: {
getText() {
return this.item[this.index];
},
},
render(createElement) {
if (this.$props.format) {
return this.$props.format(this.item, this.index, createElement);
}
return createElement('div', this.getText());
},
};
</script>

问题发生在这里:

this.$set(this.items[0], 'selected', true);

但是,如果我像这样遵循文档:

<template>
<div>
<v-data-table
:headers="headers"
:items="tableRows"
:search="search"
:key="tableKey"
:pagination.sync="pagination"
disable-initial-sort
rowKey
>
...
</template>
<script>
export default {
name: 'BaseTable',
props: {
headers: Array,
items: Array,
search: String,
tableKey: String,
rowKey: String,
},
...
computed: {
tableRows() {
const rows = [...this.items];
return rows;
},
},
...
methods: {
...
highlightFirst(items) {
this.selectedCode = this.items[0][this.rowKey];
this.$set(this.tableRows[0], 'selected', true);
},
},
updated() {
if (this.selectedCode === -1 && (typeof this.tableRows === 'object') && this.tableRows.length > 0) {
this.highlightFirst(this.tableRows);
}
},
};
</script>

我仍然收到错误,特别是在updated()钩子和highlightFirst()方法中,即使我没有引用或改变道具。我还需要更改什么才能摆脱此错误?

我最终解决这个问题的方法是发出一个事件并使用父组件中的row值:

clicked(row) {
window.scrollTo(0, 0);
this.selectedCode = row[this.rowKey];
this.$emit('rowClick', row);
},

但是,对于上面@Jesper的观点,从那时起,我一直在需要断开与 Vuex 的链接的情况下使用Object.assign()

最新更新