源码
store\loveTalk.ts
import {defineStore} from 'pinia'
import axios from "axios";
import {nanoid} from 'nanoid'
/*
export const useTalkStore = defineStore('talk',{ //选项式写法
//
actions:{
//用了 await, 补上 async 英 [ə'zɪŋk]美 [ə'zɪŋk]
async getATalk() {
let {data:{content:title}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
// 把请求回来的字符串,包装成一个对象
let obj = {id:nanoid(), title}
// 放到数组中
this.talkList.unshift(obj)
}
},
// 真正存储数据的地方
state(){
return {
//... as string 直接断言为 字符串
//talkList: JSON.parse(localStorage.getItem('talkList') as string) //把字符串转为对象
//如果有就用,没有则默认为空数组[]
talkList: JSON.parse(localStorage.getItem('talkList') as string) || []
}
}
})
*/
import {reactive} from 'vue'
//组合式写法
export const useTalkStore = defineStore('talk', ()=>{
//正常定义数据
//talkList就是state
const talkList = reactive(
JSON.parse(localStorage.getItem('talkList') as string) || []
)
//直接把上面的 actions 的函数拿过来:
//getATalk() 相当于 action
//用了 await, 补上 async 英 [ə'zɪŋk]美 [ə'zɪŋk]
async function getATalk() {
let {data:{content:title}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
// 把请求回来的字符串,包装成一个对象
let obj = {id:nanoid(), title}
// 放到数组中
talkList.unshift(obj)
}
return {talkList, getATalk}
})
