import { defineStore } from 'pinia'
import axios from 'axios'
export const useStore = defineStore({
id: 'example',
state: () => ({
data: []
}),
actions: {
fetchData(params) {
return axios.get('/api/data', { params })
.then(res => {
this.data = res.data
})
}
}
})
import { defineStore } from 'pinia'
import axios from 'axios'
export const useStore = defineStore({
id: 'example',
state: () => ({
data: []
}),
actions: {
fetchData(params) {
const queryString = Object.entries(params).map(([key, value]) => `${key}=${value}`).join('&')
return axios.get(`/api/data?${queryString}`)
.then(res => {
this.data = res.data
})
}
}
})
在上面的代码中,将参数以键值对的形式存入数组,并用 map 方法将其转化为字符串,最后用 join 方法将其组合成 Query String,以拼接到请求地址的后面。