Vite+Vue3+Pinia学习笔记

项目中安装pinia

yarn add pinia
# 或者使用 npm
npm install pinia
// main.js中引入
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);

// vue使用pinia
import { createPinia } from "pinia"
app.use(createPinia());

定义store,渲染state

在 src 目录下新建 store 目录,store 目录下新建 demo.ts

import { defineStore } from 'pinia';

export const demoStore = defineStore('demo', {
  state: () => {
    return {
      // 所有这些属性都将自动推断其类型
      counter: 0 as Number,
      mobile:"13111111111" as String
    }
  },
  getters:{},
  actions:{}
})

在页面组件中渲染 state





修改state的几种方式

// 修改上面代码



// 接上述代码片段4.actions修改state
// store/demo.ts

import { defineStore } from 'pinia';

export const demoStore = defineStore('demo', {
  state: () => {
    return {
      // 所有这些属性都将自动推断其类型
      counter: 0 as Number,
      mobile:"13111111111" as String
    }
  },
  getters:{},
  actions:{
    // 4.改变state值
    add(n:number){
      this.counter += n;
    },
    reduce(n:number){
      this.counter -= n;
    }
  }
})

Getters的使用

// store/demo.ts

import { defineStore } from 'pinia';

export const demoStore = defineStore('demo', {
  state: () => {
    return {
      // 所有这些属性都将自动推断其类型
      counter: 0 as Number,
      mobile:"13111111111" as String
    }
  },
  getters:{
    mobileHidden:(state):String => {
      return state.mobile.replace(/(\d{3})\d{4}(\d{4})/g,`$1****$2`);
    }
  },
  actions:{
    // 4.改变state值
    add(n:number){
      this.counter += n;
    },
    reduce(n:number){
      this.counter -= n;
    }
  }
})
// 页面组件中使用同state





store互调

store 目录下新建 test.ts 作为第二个 store

// store/test.ts

import { defineStore } from 'pinia';

export const testStore = defineStore('test', {
  state: () => {
    return {
      list:[1,2,3] as Array
    }
  },
  getters:{},
  actions:{}
})
// store/demo.ts

import { defineStore } from 'pinia';
// 引入testStore
import { testStore } from './test';
import { toRaw } from "vue";

export const demoStore = defineStore('demo', {
  state: () => {
    return {}
  },
  getters:{},
  actions:{
    // store互调
    getList(){
        // 需要先将testStore调用实例化,然后读取里面state
        console.log(toRaw(testStore().list))
    }
  }
})


你可能感兴趣的:(#,vue,学习,vue3,TypeScript,Pinia)