簡體   English   中英

Vue - 如何從 Vuex 訪問組件的屬性

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

在我的應用程序中,我使用 Vuex 來執行異步任務。 在這種情況下,我使用它來將用戶登錄到我的應用程序。 當用戶登錄並執行 axios.then() 時,我想通知我從中調用 this.$store.dispatch('login', {username: userObj.username, password: userObj.password}); 我的組件:


    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
                });
        }
    },

視圖:

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')
            });
    },
}

在這里,in.then() 方法我想以某種方式將組件中的測試屬性更改為 true。 有人可以幫我解決這個問題嗎?

您可以從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);
                });
        })
    },
}

當你調度 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*/);

擁有 Vuex 商店的全部意義不是改變你的組件道具/數據。 相反,您應該將數據存儲在 Vuex 中並監聽組件中的更改/更新。 因此,在您的登錄操作中,您應該具有以下內容:

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

然后,在組件中:

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

Vuex 動作是可以的,所以基本上你在組件中的動作分派應該是這樣的:

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

此外,您的操作必須返回響應才能使其正常工作。

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')
            });
    },
}

對於突變,您可以使用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