首页 > 解决方案 > 如何在 Vue.js 中处理 Vuex 数组

问题描述

我是一名新的网络开发人员。我需要帮助从数组中的所有对象中获取所有标题。我从 axios 请求中获得了一系列产品。在下一步中,我需要在 Vue 组件中处理这个数组并将单个值记录到数据中。接下来我需要在多选的选项中显示这个数据值。

这是axios代码:

async getOrders(ctx, data)
{
    return new Promise((resolve, reject) => {
        axios({
            url: '/orders',
            data: data,
            method: 'GET'
        })
            .then((resp) => {
                ctx.commit('setOrders', resp.data.orders)
                ctx.commit('setUsers', resp.data.users)
                ctx.commit('setProducts', resp.data.products)
                ctx.commit('updatePagination', resp.data.pagination)
                resolve(resp)
            })
            .catch((error) => {
                console.log(error)
                reject(error)
            })
    })
},

这是我在 Vuex 商店中记录的产品数组

0: {id: 6, category_id: 2, title: "Test", brand: "Тест", serial_number: "2165412315864",…}

1: {id: 7, category_id: 3, title: "Климат", brand: "Климат", serial_number: "2165412315864",…}

2: {id: 8, category_id: 5, title: "New", brand: "New", serial_number: "2165412315864",…}

这是我处理这个数组的代码

computed:{
        ...mapGetters('order', ['users', 'products',  'orders']),
    },
    methods:{
        getProducts(products)
        {

            const arr = products.map(c => c.title)
            console.log('titles: ', arr); //Debug
            this.options = arr
        }

    },

这是多选的代码

<multiselect v-model="formData.product" :options="options" :value="values" :multiple="true" :close-on-select="false" :clear-on-select="false" :preserve-search="true" placeholder="Pick some" label="name" track-by="name" :preselect-first="true">
                                            <template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} options selected</span></template>
                                        </multiselect>



mounted() {
        this.getProducts();
    },

标签: vue.jsaxiosvuex

解决方案


看起来你并没有通过调用来发送你的 args this.getProducts()。不需要,只要写this.在方法内计算值的前面即可。

methods: {
    getProducts () {
        const arr = this.products.map(c => c.title)
        this.options = arr
    }
}

推荐阅读