我们通过创建一个简单的demo,来认识下pinia .
....安装创建项目
npm init vite@latest
npm install pinia
....引用store
import { createPinia } from 'pinia'
const pinia = createPinia()
const app =createApp(App)
app.use(pinia)
app.mount('#app')
....创建stroe
import { defineStore} from 'pinia'
export const mainStore = defineStore('main',{
state:()=>{
return {}
},
getters:{},
actions:{}
})
....使用stroe
import { mainStore } from "../store/index";
const store = mainStore();
setInterval(function( ) {
store.$patch({
helloWorld: "helloWddorld"
});
store.changeState()
},1000)
vite可以创建多种程序。这里选择vue,和ts,创建好了,再安装pinia
npm install pinia
1、在项目中引入
import { createPinia } from 'pinia'
// createApp(App).mount('#app')
const pinia = createPinia()
const app =createApp(App)
app.use(pinia)
app.mount('#app')
2、创建store/index.ts
import { defineStore} from 'pinia'
export const mainStore = defineStore('main',{
state:()=>{
return {}
},
getters:{},
actions:{}
})
3、添加数据到Store
state:()=>{
return {
helloWorld:'Hello World'
}
},
4、添加代码到components/Test.vue
<template>
<h2 class="">{{ store.helloWorld }}</h2>
</template>
<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();
</script>
<style lang="scss" scoped></style>
?5、 引用到app.vue里。就可了
<script setup lang="ts">
import Test from './components/Test.vue'
</script>
<template>
<test></test>
</template>
?
?6、写个action在store里。然后直接在页面里调用。
actions:{
changeState(){
this.count++
this.helloWorld='Hello1'
}
}
?
<script lang="ts" setup>
import { mainStore } from "../store/index";
const store = mainStore();
setInterval(function( ) {
store.$patch({
helloWorld: "helloWddorld"
});
store.changeState()
},1000)
</script>
|