【发布时间】:2020-09-11 05:52:06
【问题描述】:
我需要在我的记录组件之外的多个地方获取记录,并且正在使用 Vuex 和挂载的调用来获取记录:
Vuex
state: {
record: null,
loaded: false,
currentRecordId: null
},
mutations: {
SET_CURRENT_RECORD_ID(state, recordId){
state.currentRecordId = recordId
}
},
actions: {
getRecord(context){
axios.get('api/thought'+this.state.currentRecordId)
.then(response => {
context.commit('SET_RECORD_DATA', response.data.data)
})
.catch(error => {
})
}
},
记录组件
mounted() {
this.getRecord()
},
methods: {
getRecord: function(){
this.$store.dispatch('getRecord');
},
}
问题在于,有时currentRecordId 状态需要来自路由参数this.$route.params.hashedId,有时它会由SET_CURRENT_RECORD_ID() 突变设置。原因是需要从各种模式和其他组件中获取记录。例如:
记录组件
<template>
<div v-for="record in records">
<button><span @click="setRecordHashedId(record.id)" class='bg-blue'> <v-icon class="mr-1">launch</v-icon> View/add details</span></button>
</div>
</template>
<script>
export default {
data: function() {
return {
records: null,
}
},
mounted() {
this.getRecords()
},
methods: {
setRecordHashedId(hashedId) {
this.$store.commit('SET_CURRENT_RECORD_ID', hashedId);
this.$router.push({ name: 'record', params: {hashedId: hashedId } })
}
}
}
</script>
那么我如何在 Vuex 中确定 currentRecordId 是来自路由参数还是突变?
【问题讨论】:
标签: vue.js vuex vue-router