简体   繁体   English

Vue - 如何从 Vuex 访问组件的属性

[英]Vue - How to access component's property from Vuex

In my app I use Vuex to perform async tasks.在我的应用程序中,我使用 Vuex 来执行异步任务。 In this case I use it to log user to my app.在这种情况下,我使用它来将用户登录到我的应用程序。 When user is logged and axios.then() is being performed I want to inform the component from which I called this.$store.dispatch('login', {username: userObj.username, password: userObj.password});当用户登录并执行 axios.then() 时,我想通知我从中调用 this.$store.dispatch('login', {username: userObj.username, password: userObj.password}); My component:我的组件:


    data() {
        test: false
    },

    methods: {

        login() {
            const userObj = {
                username: this.username,
                password: this.password
            };
            console.log(userObj);
            this.$store.dispatch('login',
                {
                    username: userObj.username, password: userObj.password
                });
        }
    },

Vuex:视图:

const actions = {
    login({ commit }, authData) {
        axios.post('/login', {
            username: authData.username,
            password: authData.password
        })
            .then(resp => {
                console.log(resp);
                localStorage.setItem('token', resp.data.authToken);
                localStorage.setItem('userId', resp.data.id);
                localStorage.setItem('user', resp.data);
                commit('storeUser', resp.data);
                router.replace('/dashboard');
            })
            .catch(e => {
                console.log(e);
                alert('Something went wrong, try again')
            });
    },
}

Here, in.then() method I want somehow to change test property in my component to true.在这里,in.then() 方法我想以某种方式将组件中的测试属性更改为 true。 Can someone help me with this one?有人可以帮我解决这个问题吗?

You can return a Promise from a vuex action:您可以从vuex操作返回一个Promise

const actions = {
    login({ commit }, authData) {
        return new Promise((resolve, reject) => {
            axios.post('/login', {
                username: authData.username,
                password: authData.password
            })
                .then(resp => {
                    console.log(resp);
                    localStorage.setItem('token', resp.data.authToken);
                    localStorage.setItem('userId', resp.data.id);
                    localStorage.setItem('user', resp.data);
                    commit('storeUser', resp.data);
                    router.replace('/dashboard');
                    resolve(resp);
                })
                .catch(e => {
                    console.log(e);
                    alert('Something went wrong, try again')
                    reject(e);
                });
        })
    },
}

When you dispatch the action you can just treat it like a Promise (because the return value is a Promise ):当你调度 action 时,你可以把它当作一个Promise (因为返回值是一个Promise ):

// inside your component
this.
  $store.
  dispatch('login', {username: userObj.username, password: userObj.password})
  .then(resp => { /* do something with axios response using component data and methods*/);

The whole point of having the Vuex store is not to change your component props/data.拥有 Vuex 商店的全部意义不是改变你的组件道具/数据。 Instead, you are supposed to store the data in Vuex and listen to the changes/updates in the component.相反,您应该将数据存储在 Vuex 中并监听组件中的更改/更新。 So, in your login action, you should have something like:因此,在您的登录操作中,您应该具有以下内容:

// Commit the changes to the store
commit('storeTest', true);

and then, in the component:然后,在组件中:

computed: {
    // Get the value from the store
    test: () => {
        return this.$store.test;
    }
},

Vuex actions are thennable, so basically your action dispatch in the component should look something like this: Vuex 动作是可以的,所以基本上你在组件中的动作分派应该是这样的:

this.$store.dispatch('login', { username: userObj.username, password: userObj.password }).then(res => {
// response handling
});

Also your action must return the response in order for it to work.此外,您的操作必须返回响应才能使其正常工作。

const actions = {
    login({ commit }, authData) {
        axios.post('/login', {
            username: authData.username,
            password: authData.password
        })
            .then(resp => {
                console.log(resp);
                localStorage.setItem('token', resp.data.authToken);
                localStorage.setItem('userId', resp.data.id);
                localStorage.setItem('user', resp.data);
                commit('storeUser', resp.data);
                router.replace('/dashboard');
                return resp
            })
            .catch(e => {
                console.log(e);
                alert('Something went wrong, try again')
            });
    },
}

For mutations уоu can use subscribe or subscribeAction for actions as such:对于突变,您可以使用subscribesubscribeAction来执行以下操作:

mounted() {
    this.$store.subscribeAction({
        before: (action, state) => {
            switch (action.type) {
                case 'login':
                    this.test = false;
                    break;
            }
        },
        after: (action, state) => {
            switch (action.type) {
                case 'login':
                    this.test = true;
                    break;
            }
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM