美文网首页
vue3 使用pinia小计

vue3 使用pinia小计

作者: Gifted_ | 来源:发表于2023-04-13 15:05 被阅读0次
    引入pinia
    import { createApp, defineAsyncComponent } from 'vue'
    import App from './App.vue'
    import { createPinia } from 'pinia'
    
    const app = createApp(App)
    const pinia = createPinia()
    app.use(pinia)
    app.mount('#app')
    
    
    新建stores.js

    setup Store语法
    与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。
    Setup Store 中:

    • ref() 就是 state 属性
    • computed() 就是 getters
    • function() 就是 actions

    Setup store 比 Option Store 带来了更多的灵活性,因为你可以在一个 store 内创建侦听器,并自由地使用任何组合式函数。不过,请记住,使用组合式函数会让 SSR 变得更加复杂。

    import { ref } from 'vue'
    import { defineStore } from 'pinia'
    //这边引入了一个aes加密用的可以不用
    import AES from '@/utils/aes.js'
    
    //根据路由设置菜单选中状态
    export const useRouteStore = defineStore('route', () => {
      const key = AES.encrypt('currentId')
      const currentId = ref('')
    
      if (!currentId.value && !sessionStorage.getItem(key)) {
        changeRoute('hszp')
      } else {
        const cur = sessionStorage.getItem(key)
        currentId.value = AES.decrypt(cur)
      }
      function changeRoute(value) {
         currentId.value = value
         sessionStorage.setItem(key, AES.encrypt(value))
       }
    
      return { currentId, changeRoute, getCurrentId }
    })
    
    使用 Store

    虽然我们前面定义了一个 store,但在我们使用 <script setup> 调用 useStore()(或者使用 setup() 函数,像所有的组件那样) 之前,store 实例是不会被创建的:

    <script setup>
    import { useCounterStore } from '@/stores/counter'
    // 可以在组件中的任意位置访问 `store` 变量 ✨
    const store = useCounterStore()
    </script>
    

    你可以定义任意多的 store,但为了让使用 pinia 的益处最大化(比如允许构建工具自动进行代码分割以及 TypeScript 推断),你应该在不同的文件中去定义 store。

    一旦 store 被实例化,你可以直接访问在 store 的 state、getters 和 actions 中定义的任何属性。

    为了从 store 中提取属性时保持其响应性,你需要使用 storeToRefs()。它将为每一个响应式属性创建引用。当你只使用 store 的状态而不调用任何 action 时,它会非常有用。请注意,你可以直接从 store 中解构 action,因为它们也被绑定到 store 上:

    <script setup>
    import { storeToRefs } from 'pinia'
    const store = useCounterStore()
    // `currentId ` 是响应式的 ref
    // 同时通过插件添加的属性也会被提取为 ref
    // 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
    const { currentId } = storeToRefs(store)
    // 作为 action 的 changeRoute 可以直接解构
    const { changeRoute} = store
    </script>
    

    相关文章

      网友评论

          本文标题:vue3 使用pinia小计

          本文链接:https://www.haomeiwen.com/subject/cjigddtx.html