使用 Vuex 4 在 Vue 3 中设置状态数据不起作用

Setting data in state not working in Vue 3 with Vuex 4

我正在使用 Vuex 4 学习 Vue 3,但我遇到了一些我很确定它很简单但我看不到的东西。

简而言之,我正在尝试在 state 中设置一些数据,以便在我的组件中使用它,但它不起作用。

让我给你看代码:

/// store.js

import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
  state: {
    user: {},
    products: []
  },
  mutations: {
    SET_USER: (state, user) => {
      state.user = user;
    },
    SET_PRODUCTS: (state, products) => {
      state.products = products;
    },
  },
  actions: {
    GET_USER: async function ({ commit }) {
      const user = await axios.get('https://coding-challenge-api.aerolab.co/user/me')
      commit('SET_USER', user)
    },
    GET_PRODUCTS: async function ({ commit }) {
      const products = await axios.get('https://coding-challenge-api.aerolab.co/products')
      commit('SET_PRODUCTS', products)
    },
  }
})

export default store;

/// MyComponent.vue

<template>
  <div class='bg-aerolab-main'>
    {{ user }} {{ productsTest }}
  </div>
</template>

import { computed } from "vue";
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();
    const user = computed(() => store.state.user);
    const productsTest = computed(() => store.state.products);
    console.log(user);
    console.log(productsTest);

    return {
      user,
      productsTest
    };
  }
}

/// main.js

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import axios from 'axios'
import VueAxios from 'vue-axios';
import store from './store';

const app = createApp(App)
  app.use(VueAxios, axios)
  app.use(store)
  app.mount('#app')

当然 {{ users }}{{ productsTest }} 绑定不显示任何数据,console.logs.

PD:我试图直接在我的组件中获取数据并且它正在工作,所以它与从 API.

获取的数据无关

您必须在 mounted 钩子中调度该操作:

import { computed , onMounted} from "vue";
import { useStore } from 'vuex';

export default{
  setup() {
    const store = useStore();
    const user = computed(() => store.state.user);
    const productsTest = computed(() => store.state.products);
   
  onMounted(()=>{
    store.dispatch('GET_USER');
    store.dispatch('GET_PRODUCTS');
  })
    return {
      user,
      productsTest
    };
  }
}

从main.js

获取数据

如果您从组件中获取数据,我相信所选答案会正常工作。但是,如果您希望按照 OP 的要求 main.js 获取数据,或者如果您使用的是 Vue3,则 app.js对于 Laravel,您应该在 createApp() 函数中使用 mounted()

const app = createApp({
    mounted(){
        store.dispatch('YOUR_ACTION') // GET_USER or GET_PRODUCTS in OP's case
    }
});

记得在调用它之前设置您的 Vuex 存储,以便定义 store

在你的组件中

您可以访问the computed state with composition API,如下图:


import { computed } from "vue";
import { useStore } from "vuex";

setup() {
        const store = useStore();
       
        return {
            products: computed(() => store.state.YOUR_STATE), 
            //replace YOUR_STATE with your own. In OP's case, it's user or products
        };
    }