Pinia的初级使用

147 阅读1分钟

1、Pinia的优势和环境安装

1、Vue3、Vue2都支持
2、抛弃了Mutations的操作,只有state、getters和actions
3、不需要嵌套模块,符合Vue3的Compontion api
4、完整的TypeScript支持
5、代码更加简洁

npm i pinia

2、使用

1、在 main.js 添加 pinia
	import { createApp } from 'vue'
    import App from './App.vue'
    import { createPinia } from 'pinia'

    const pinia = createPinia()
    const app = createApp(App)

    app.use(pinia)
    app.mount('#app')
    
2、在 src 下新建文件夹 store
3、新建 index.js
    // 1、定义状态容器
    // 2、修改容器的 state
    // 3、仓库中的 action 的使用

    import { defineStore } from 'pinia'
    import { jspangStore } from './jspang'

    export const mainStore = defineStore('main', {
      state: () => {
        return {
          helloWorld: 'hellow world!',
          count: 0,
          phone: '19970248614'
        }
      },
      getters: {
        phoneHidden(state) {
          console.log('getters 被调用了');

          return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
        }
      },
      actions: {
        changeState() {
          this.count++
          this.helloWorld = this.helloWorld === 'tjf' ? 'hello world!' : 'tjf'
        },
        getList() {
          console.log(jspangStore().list);

        }
      }
    })
   
4、展示
    <template>
      <div>{{ store.helloWorld }}</div>
      <div>{{ store.count }}</div>
      <div>响应式解构count:{{ count }}</div>
    </template>

    <script setup lang="ts">
        import { mainStore } from '../store/index'
        import { storeToRefs } from 'pinia'

        const store = mainStore()
        const { count } = storeToRefs(store)
    </script>
    
5、操作
    <script setup lang="ts">
    import { mainStore } from '../store/index'
    const store = mainStore()

    // 第一种方法
    const handleClick = () => {
      store.count++
    }

    // 第二种方法 $patch
    const handleClickPatch = () => {
      store.$patch({
        count: store.count + 2,
        helloWorld: store.helloWorld === 'tjf' ? 'hello world!' : 'tjf'
      })
    }

    // 第三种方式 $patch 传递函数
    const handleClickMethod = () => {
      store.$patch((state) => {
        state.count++
        store.helloWorld = store.helloWorld === 'tjf' ? 'hello world!' : 'tjf'
      })
    }

    // 第四种方式 actions
    const handleClickAction = () => {
      store.changeState()
    }

    const handleClickChangePhone = () => {
      store.phone = '18079717346'
    }

    const getList = () => {
      store.getList()
    }

    </script>

6、store 相互调用
	import { jspangStore } from './jspang' //引入 pinia 文件
	
	------
	
	actions: { //在actions里面调用
      getList() {
        console.log(jspangStore().list);

      }
    }