Pinia 计数器

新增stores目录

在stores目录里面新增一个counter.js 文件

文件代码:

import { defineStore } from 'pinia

export const useCounterStore = defineStore('counter',{
  state:()=>{
     return { count:0 }
    
  },
  //也可以这样定义
  //state:() => ({ count : 0})
  actions: {

    increment() {
    
       this.count++
    }

 }

})

在组件中使用

import { useCounterStore } from '@stores/counter'

export default {
   setup() {
     const counter = useCounterStore() //初始化 counter对象
     counter.count++
     //带有自动补全
     counter.$patch({ count : counter.count+1 })
     //或者用action代替
     counter.increment()


  }

}

或者更高级的定义store

//定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore ('counter',()=>{
    
   //数据(state)
   const count = ref(0)
   
   //修改数据的方法 (action)
   const increment = () =>{
      count.value++

   }

   //以对象形式返回
   return {count . increment}

})

然后在组件里使用Store



总结:

1、定义store (使用导入的useCounterStore)

2、组件中使用

在vuex中getters为计算属性

getters在pinia中实现,直接使用computed函数进行模拟

// 数据 (state)
const count = ref(0)

//getter
const doubleCount = computed(() => count.value * 2)

在state里面加入getter

//定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore ('counter',()=>{
    
   //数据(state)
   const count = ref(0)
   
   //修改数据的方法 (action) 同步+异步
   const increment = () =>{
      count.value++
      
   }
   
   //getter定义
   const doubleCount = computed(() => count.value*2)


   //以对象形式返回 供组件使用
   return {count,
           increment,
           doubleCount  //在return 对象里加入

    }

})


异步action

//定义异步 action

 const list = ref([])

const getlist = async ()=>{

   const res = await axios.get(API_URL)

}

同理要在return 里返回

//定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore ('counter',()=>{
    
   //数据(state)
   const count = ref(0)
   
   //修改数据的方法 (action) 同步+异步
   const increment = () =>{
      count.value++
      
   }

   //定义异步 action

   const list = ref([])

   const getList = async ()=>{

      const res = await axios.get(API_URL)

   }   

   //getter定义
   const doubleCount = computed(() => count.value*2)


   //以对象形式返回 供组件使用
   return {count,
           increment,
           doubleCount,  //在return 对象里加入
           getList
           
    }

})

不用对象+.的形式取 用解构赋值

但是一般的解构赋值会丢失响应式 那么应该怎么办呢

import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore


//然后用这个方法包裹一下(保持响应式更新)

const {count , doubleCount} = storeToRefs(counterStore)


包裹后产出的是两个ref对象,而不是解构的值

那么方法能不能解构赋值 (响应式) 方法要用一般解构赋值的写法才可以 不能用storeToRefs方法包裹

Pinia调试

总结:

1、Pinia 是用来做什么的?

集中状态管理工具,新一代的vuex

2、Pinia中还需要mutation吗?

不需要,action既支持同步也支持异步

3、Pinia如何实现getter

computed计算属性函数

4、Pinia产生的Store如何解构赋值数据保持响应式?

storeToRefs

你可能感兴趣的:(前端,javascript,html)