语法
2023年05月15日
一、setup store
2.1 main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from "pinia"
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app')
2.2 useGlobalState.ts
import { computed, ref } from "vue";
import { defineStore } from "pinia"
export const useGlobalState = defineStore('globalState',()=>{
const a = ref(1);
const countA = computed(()=>{
return a.value * 2;
});
function setA(value:number){
a.value += value;
}
return { a, countA, setA}
});
在 setup state
中:
-
ref()
: 就是steate
的属性 -
computed()
: 就是getter
-
function
: 就是actions
2.3 App.vue 使用全局状态
<template>
<div>
{{ store.a }}
{{ store.countA }}
<Child></Child>
</div>
</template>
<script setup lang="ts">
import Child from './Child.vue'
import { useGlobalState } from './stores/useGlobalState';
const store = useGlobalState();
</script>
2.4 Child.vue 改变全局状态
<template>
<div>
{{ store.a }}
<button @click="store.setA(10)">按钮</button>
</div>
</template>
<script setup lang="ts">
import { useGlobalState } from './stores/useGlobalState';
const store = useGlobalState();
</script>
二、option store
2.1 main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from "pinia"
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app')
2.2 useGlobalState.ts
import { defineStore } from "pinia"
export const useGlobalState = defineStore('globalState',{
state:()=>{
return {
a: 1,
b: 2,
c: 3
}
},
getters: {
countA(state){
return state.a * 2;
},
countB(state){
return state.b + 2;
}
},
actions: {
setA(value: number){
this.a += value;
},
setB(value: number){
return new Promise((resolve)=>{
setTimeout(()=>{
this.b -= value;
resolve(this.b);
},2000)
});
}
}
});
Option Store
可以传入一个带有 state
、actions
与 getters
属性的 Option
对象。
-
state
:store
的数据(data)
-
getters
:store
的计算属性(computed)
-
actions
:actions
是方法(methods)
2.3 App.vue 使用全局状态
<template>
<div>
{{ store.a }}
{{ store.countA }}
<Child></Child>
</div>
</template>
<script setup lang="ts">
import Child from './Child.vue'
import { useGlobalState } from './stores/useGlobalState';
const store = useGlobalState();
</script>
2.4 Child.vue 改变全局状态
<template>
<div>
{{ store.a }}
<button @click="store.setA(10)">按钮</button>
</div>
</template>
<script setup lang="ts">
import { useGlobalState } from './stores/useGlobalState';
const store = useGlobalState();
</script>