https://pinia.vuejs.org/getting-started.html

1、安装

  1. cnpm i pinia -S
  2. cnpm i

2、vue2中main.js中配置

  1. import Vue from 'vue'
  2. ...
  3. import {createPinia,PiniaVuePlugin} from 'pinia'
  4. Vue.use(PiniaVuePlugin);
  5. const pinia = createPinia()
  6. new Vue({
  7. ...
  8. pinia,
  9. }).$mount("#app")

3、store/index.js

  1. import {defineStore} from 'pinia'
  2. export const useStore = defineStore('store',{
  3. state:()=>{
  4. return {
  5. count:1
  6. }
  7. },
  8. actions:{
  9. addCount(){
  10. this.count++
  11. }
  12. }
  13. })

4、组件中使用

  1. <template>
  2. <div>
  3. Home
  4. <button @click="addCount">{{count}}</button>
  5. </div>
  6. </template>
  7. <script>
  8. import {mapActions, mapState} from 'pinia'
  9. import {useStore} from '@/store'
  10. export default {
  11. computed:{
  12. ...mapState(useStore,['count'])
  13. },
  14. methods:{
  15. ...mapActions(useStore,['addCount'])
  16. }
  17. }
  18. </script>