【问题标题】:pass computed property as method parameter?将计算属性作为方法参数传递?
【发布时间】:2018-02-05 00:38:07
【问题描述】:

所以我有一个价值商店:

export const store = new Vuex.Store({
    state: {
        selectedGradeId: null,
    },
    getters:{
        selectedGradeId: state => {
            return state.selectedGradeId
        },
    },
    mutations:{
        SET_SELECTED_GRADE_ID(state, gradeid){
            state.selectedGradeId = gradeid
        },
        CLEAR_SELECTED_GRADE_ID(state){
            state.selectedGradeId = null
        },       
    },
    actions:{
        loadStudentsForGrade (gradeId) {
                return new Promise((resolve, reject) => {
                    axios.get('/students/'+gradeId)
                        .then((response)=>{
                            ... do stuff
                            resolve(response)
                        }, response => {
                            reject(response)
                        })
                })
        },
    }
})

在我的组件中,我基本上有一个选择来加载特定年级的学生列表:

<select id="grades" name="grades" v-model="selectedGradeId" @change="loadStudentsForGrade(selectedGradeId)"

methods: {
            loadStudentsForGrade(gradeId) {
                this.$store.dispatch('loadStudentsForGrade', {gradeId})
                    .then(response => {             
                }, error => {                   
                })
            },
        },
        computed: {
            selectedGradeId: {
                get: function () {
                    return this.$store.getters.selectedGradeId;
                },
                set: function (gradeId) {
                    this.$store.commit('SET_SELECTED_GRADE_ID', gradeId);
                }
            },          

        }

当在我的组件中调用“loadStudentsForGrade”方法时,它会将“selectedGradeId”作为参数,这是一个计算属性。 现在我遇到的问题是,在我的商店中,“loadStudentsForGrade”操作获取了一个对象(我猜是计算的?)而不仅仅是gradeid

我得到的对象被打印到控制台: {dispatch: ƒ, commit: ƒ, getters: {...}, state: {...}, rootGetters: {...}, ...}

【问题讨论】:

  • 如果您通过计算的 settergradeId 设置到存储中,为什么还要将其传递给 loadStudentsForGrade 操作呢?把它从状态中拉出来
  • 是的,很好,我什至没看到,谢谢

标签: vue.js vuex


【解决方案1】:

action 的第一个参数是 store,第二个参数是 payload。 所以你应该这样做:

actions:{
    // here: loadStudentsForGrade (store, payload) {
    loadStudentsForGrade ({ commit }, { gradeId }) {
            return new Promise((resolve, reject) => {
                axios.get('/students/'+gradeId)
                    .then((response)=>{
                        //... do stuff
                        //... commit('', response);
                        resolve(response)
                    }, response => {
                        //... commit('', response);
                        reject(response)
                    })
            })
    },
}

文档中的相关页面: https://vuex.vuejs.org/en/actions.html#dispatching-actions

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2010-11-13
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多