Pinia。新建 `store.js` 文件,配置状态变量。有两种方式,一是和 vue 的选项式 script 类似,二是和 vue 的组合式(setup)script 类似。建议用第二种方式,更简洁易读。第二种
怎么用
新建 store.js 文件,配置状态变量。有两种方式,一是和 vue 的选项式 script 类似,二是和 vue 的组合式(setup)script 类似。建议用第二种方式,更简洁易读。第二种方式如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
// store.ts
export const userStore = defineStore('user', () => {
const username = ref<string>('');
const password = ref<string>('');
return {
username,
password
}
}, {
// 注意 defineStore 的第三个参数可以传入插件配置
persist: true
})
|
调用状态变量
1
2
3
4
5
6
7
8
|
// xxx.vue
<script>
import { userStore } from 'store.ts';
const store = userStore();
const username = store.username;
const password = store.password;
</script>
|