【问题标题】:How can I determine state based on whether or not it's coming from a route param or a mutation?如何根据它是来自路由参数还是突变来确定状态?
【发布时间】: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


    【解决方案1】:

    为什么不在您的操作中为 ID 使用有效负载参数,如果未设置则回退到您的状态中的那个?

    actions: {
      getRecord: async ({ commit, state }, recordId) => {
        const url = `api/thought${encodeURIComponent(recordId ?? state.currentRecordId)}`
        const { data: { data } } = await axios.get(url)
        commit('SET_RECORD_DATA', data)
      }
    }
    

    那么你可以用任何一种方式调度

    this.$store.dispatch("getRecord") // use state.currentRecordId
    // or
    this.$store.dispatch("getRecord", this.$route.params.hashedId)
    

    如果您的环境不支持 null coalescing operator (??),请尝试此旧选项

    recordId = typeof recordId !== "undefined" ? recordId : state.currentRecordId
    const url = `api/thought${encodeURIComponent(recordId)}`
    

    【讨论】:

    • 感谢您的回答。这是最好的方法,但由于某种原因,我在 VScode 中得到了一个表达式expected error ":"。抱歉,我是 encodeURIComponent 的新手
    • @KyleCorbinHurst 在哪一行?
    • const url = api/thought${encodeURIComponent(recordId ?? state.currentRecordId)}``
    • 嗯,可能是null coalescing operator。作为测试,请尝试const url = `api/thought${encodeURIComponent(recordId || state.currentRecordId)}`。我很惊讶 VSCode 显示了一个警告。也许它需要更新或您的 ES 级别设置得太低
    猜你喜欢
    • 2018-10-18
    • 2016-01-28
    • 2014-01-02
    • 1970-01-01
    • 2013-11-06
    • 2021-02-24
    • 1970-01-01
    • 2016-09-03
    • 2011-11-03
    相关资源
    最近更新 更多