面试题答案
一键面试- 确保异步操作按顺序执行
- 使用
async/await
:在actions
中定义异步函数,利用async/await
的特性,在一个await
操作完成后再执行下一个。例如:
import { defineStore } from 'pinia'; import axios from 'axios'; export const useMyStore = defineStore('myStore', { state: () => ({ data1: null, data2: null }), actions: { async fetchData() { try { const response1 = await axios.get('/api/data1'); this.data1 = response1.data; const response2 = await axios.get('/api/data2'); this.data2 = response2.data; } catch (error) { // 错误处理 console.error('Error fetching data:', error); } } } });
- 使用
Promise.then
链式调用:虽然async/await
更现代,但Promise.then
也能实现顺序执行。例如:
export const useMyStore = defineStore('myStore', { state: () => ({ data1: null, data2: null }), actions: { fetchData() { axios.get('/api/data1') .then(response1 => { this.data1 = response1.data; return axios.get('/api/data2'); }) .then(response2 => { this.data2 = response2.data; }) .catch(error => { // 错误处理 console.error('Error fetching data:', error); }); } } });
- 使用
- 保证state状态更新的一致性
- 使用事务(Transaction - like behavior):Pinia没有内置事务概念,但可以通过将多个状态更新操作放在同一个
async
函数中,利用await
确保前一个异步操作完成后再更新状态。例如在上述fetchData
函数中,先等待axios.get('/api/data1')
完成并更新data1
,再进行axios.get('/api/data2')
并更新data2
。这样可以保证在更新data2
时,data1
已经是最新的。 - 不可变数据更新:尽量使用不可变数据更新方式,例如使用展开运算符(
...
)创建新对象或数组来更新state
。例如:
// 假设state中有一个数组items actions: { updateItems(newItem) { this.items = [...this.items, newItem]; } }
- 使用事务(Transaction - like behavior):Pinia没有内置事务概念,但可以通过将多个状态更新操作放在同一个
- 捕获异步操作的错误并处理
- 使用
try/catch
:在async
函数中使用try/catch
块捕获错误。如上述fetchData
函数中的try/catch
块,在捕获到错误后,可以进行日志记录(如console.error
),也可以在state
中设置一个错误标志,以便在组件中进行相应提示。例如:
export const useMyStore = defineStore('myStore', { state: () => ({ data1: null, data2: null, error: null }), actions: { async fetchData() { try { const response1 = await axios.get('/api/data1'); this.data1 = response1.data; const response2 = await axios.get('/api/data2'); this.data2 = response2.data; this.error = null; } catch (error) { this.error = error.message; console.error('Error fetching data:', error); } } } });
- 使用
.catch
:在使用Promise.then
链式调用时,通过.catch
捕获错误,如上述fetchData
函数使用Promise.then
方式中的.catch
块,同样可以进行日志记录或设置错误标志等处理。
- 使用