以一个简单的例子,来讲解安装,创建,到销毁Pinia一条龙
安装方式
yarn add pinia
# or with npm
npm install pinia
创建文件
在src目录下面,创建store文件夹,再创建report.js。名字随意改就好,记住后面用到report的地方统一就好了。
创建Pinia
在report.js里面写入以下代码
import {defineStore} from 'pinia'; //引入Pinia
export const report = defineStore('report', { //defineStore有两个参数
//第二个参数里面有以下三个值
//状态State
state: () => ({ //在此定义数据
reportInfo: null,
}),
//获取getters
getters: {},
//动作
actions: { //写入方法
setReportInfo(data) { //在获取到接口数据时调用此方法,将接口数据存入到reportInfo里面
let info = {}
Object.assign(info, data)
this.reportInfo= info
},
clearReportInfo() { //在需要清空数据的地方调用此方法,将销毁reportInfo里面的值
this.reportInfo = null
}
}
}
)
访问
在你想要使用的页面引入并使用
import {report} from "@/store/report";
const storeReport = report()
storeReport.setReportInfo(form) //将form存入到store里面
let id = null
id = storeReport.reportInfo.id //使用
storeReport.clearReportInfo() //销毁