0
点赞
收藏
分享

微信扫一扫

Vue3中使用pinia

幺幺零 2022-09-24 阅读 257

目录

1、安装:npm install pinia

2、创建store文件并配置内部的index.js文件

3、main.js文件中配置

4、组件使用

4-1、 store.$reset()  

 4-2 store.$patch

 5.订阅修改

6.Getter

7、Actions


1、安装:npm install pinia

2、创建store文件并配置内部的index.js文件

3、main.js文件中配置

4、组件使用

toRefsicon-default.png?t=M85Bhttp://t.csdn.cn/pLB5f

4-1、 store.$reset()  

 4-2 store.$patch

 5.订阅修改

//可以通过 store 的 $subscribe() 方法查看状态及其变化,通过patch修改状态时就会触发一次
store.$subscribe((mutation, state) => { 
  // 每当它发生变化时,将整个状态持久化到本地存储
  localStorage.setItem('test', JSON.stringify(state))
})

6.Getter

Getter 完全等同于 Store 状态的 计算值。 它们可以用 defineStore() 中的 getters 属性定义。 他们接收“状态”作为第一个参数以鼓励箭头函数的使用:(ps:虽然鼓励但是依然提供了非es6玩家的使用方式 内部可以用this代表state)

//store/index.js文件
export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
})

//组件中直接使用:  <p>Double count is {{ store.doubleCount }}</p>

7、Actions

在pinia中没有提供mutaion 因为Actions就够了(它可以异步同步的统一修改状态)

之所以提供这个功能 就是为了项目中的公共修改状态的业务统一

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++//1.有this
    },
    randomizeCounter(state) {//2.有参数   想用哪个用哪个
      state.counter = Math.round(100 * Math.random())
    },
    randomizeCounter(state) {
        //异步函数
        axios("/test").then(res=>{
             state.counter = res.data.length
        })
     
    }
  },
})

//组件中的使用:
  setup() {
    const store = useStore()
    store.increment()
    store.randomizeCounter()
  }
举报

相关推荐

0 条评论