Home  >  Article  >  Web Front-end  >  How to introduce and use Pinia repository in Vue3

How to introduce and use Pinia repository in Vue3

WBOY
WBOYforward
2023-05-14 19:13:041777browse

1. Install in your favorite way

yarn add pinia
# 或者使用 npm
npm install pinia

2.Introduce main.js

import { createApp } from 'vue'
import App from './App.vue'
 
const app=createApp(App)
import { createPinia } from 'pinia' //引入pinia
app.use(createPinia())
 
app.mount('#app')

3.Create the store file and configure the internal index.js file

import { defineStore } from 'pinia' //引入pinia
 
//这里官网是单独导出  是可以写成默认导出的  官方的解释为大家一起约定仓库用use打头的单词 固定统一小仓库的名字不易混乱
export const useCar=defineStore("test",{ 
    state: () =>{
        return  ({
            msg:"这是pinia",
            name:"小小",
            age:18
            }) //为了避免出错,返回的值用()包起来
    } 
})

4. How to use components

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="modify">修改store.name</button>
</template>
 
<script>
import { defineComponent, ref } from &#39;vue&#39;;
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        modify(){
             store.name = state.testMsg //修改pinia里面的数据
             console.log(store.name)
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

5. Reset store.$reset()

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="reset">重置store.name</button>
</template>
 
<script>
import { defineComponent, ref } from &#39;vue&#39;;
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        reset(){
             store.$reset() //重置pinia里面的数据
             console.log(store.name)
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

6. Group modification store.$patch can modify pinia’s data in the same way

Features: Batch modification but the status is only refreshed once

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="modify">修改store.name</button>
    <button @click="reset">重置store.name</button>
    <button @click="allModify">群体修改store.name</button>
</template>
 
<script>
import { defineComponent, ref } from &#39;vue&#39;;
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        modify(){
             store.name = state.testMsg //修改pinia里面的数据
             console.log(store.name)
        },
        reset(){
             store.$reset() //重置pinia里面的数据
             console.log(store.name)
        },
        allModify(){
             store.$patch({
              name:"花花",
              age:20,
            })
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

7. Subscription modification

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

8.Getter

Getter is completely equivalent to the calculated value of the Store status. They can be defined using the getters attribute in defineStore(). They receive "state" as the first parameter to encourage the use of arrow functions: (ps: Although it is encouraged, it still provides usage methods for non-es6 players. Internally, this can be used to represent state)

//store/index.js文件
export const useStore = defineStore(&#39;main&#39;, {
  state: () => ({
    counter: 0,
  }),
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
})
 
//组件中直接使用:  <p>Double count is {{ store.doubleCount }}</p>

9.Actions

There is no mutaion provided in pinia because Actions are enough (it can modify the status asynchronously and synchronously). The reason why this function is provided is for the business unification of the public modification status in the project

export const useStore = defineStore(&#39;main&#39;, {
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++//1.有this
    },
    randomizeCounter(state) {//2.有参数   想用哪个用哪个
      state.counter = Math.round(100 * Math.random())
    },
    randomizeCounter(state) {
        //异步函数.接口成功赋值
     ajax.hplBaseApi("app/productSelection/categoryRows", {}, "post").then((res) => {
        state.counter = res.data.length
     });
    }
  },
})
 
//组件中的使用:
  setup() {
    const store = useStore()
    store.increment()
    store.randomizeCounter()
  }

The above is the detailed content of How to introduce and use Pinia repository in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete