如何在商店对象中访问父Vue页面?

时间:2020-02-20 07:05:10

标签: vue.js vuejs2 vuex vee-validate

在我的vue 2.6 / cli 4 / vuex 3.1应用程序中,我更新了商店vuex中的一些数据,例如src / store / index.js中的数据:

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        self.$refs.userObserverForm.setErrors(error.body.errors)
    });
}, // userPropStore(context, userProp ) {

,并使用vee-validate 3.2的ValidationProvider,我想捕获服务器错误(例如不是唯一项) 但我收到错误消息:

index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined

在线

self.$refs.userObserverForm.setErrors(error.body.errors)

如果存储对象中有一种方法可以访问父页面(可能带有上下文),则具有:https://imgur.com/a/P4St8Ri

谢谢!

2 个答案:

答案 0 :(得分:1)

这是一个非常奇怪的实现。

很显然self.$refs.userObserverForm.setErrors(error.body.errors)失败,因为您不在组件中,而$ refs可用。

您需要在catch块中进行的工作是在Vuex中设置错误,然后从那里读取组件。

伪代码如下:

我不知道您的总线在做什么……我想您是用它来向组件发送数据的,但是为什么要使用Vuex

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
        let userProps= this.getters.userProps
        userProps.push({
            "id": data.user_props.id,
            "name": data.user_props.name,
            "value": data.user_props.value,
            "created_at": data.user_props.created_at,
        })
        this.commit('refreshUserProps', userProps);
        bus.$emit( 'onUserPropStoreSuccess', data );
        commit('SET_USER_PROPS, data)
    }, error => {
        console.log('context::')
        console.log(context)
        console.error(error)
        commit('SET_USER_PROPS_ERRORS', error.body.errors)
    });
}

答案 1 :(得分:0)

我过去这样做的方式是返回Vue.http.post产生的承诺,然后使用故障信息在组件中做您想做的事情:

userPropStore(context, userProp ) {
    bus.$emit( 'beforeUserPropStore', userProp );
    let apiUrl = process.env.VUE_APP_API_URL
    //add return to the line below
    return Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {

然后在您的组件中浏览

loadData() {
    this.$store.dispatch('userPropStore').catch((error) => {
        this.$refs.userObserverForm.setErrors(error.body.errors)
        //any other things you want to do "in component" goes here
    });
}