pinia从0到1

一、创建项目

  1. npm create vite@latest

  2. 输入项目名称

  3. cd 到新建的项目

  4. npm install 安装项目依赖

  5. npm run dev 运行项目

二、安装Pinia

复制代码
npm install pinia

三、在main.js中挂载

1.引入pinia

import {createPinia} form "pinia";

2.创建pinia对象

const pinia = createPinia();

3.挂载实例

app.use(pinia).mount('#app');

四、创建store

复制代码
//     ./src/store/index.js
// 1.引入pinia对象
import {defineStore} from 'pinia';

// 2.创建管理状态仓库
export const useStore = defineStore("store", {
    // 选项式,更接近于vuex
    state: () => {
        return {
            num: 1,
            name: 'gxy',
        }
    },
    getters: {},
    actions: {}
})

五、在组件中使用选项式store

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"
  // 2.声明
  const store= useStore();

</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>name:{{ store.name }}</p>
</template>

<style scoped>

</style>

六、组件中修改pinia数据

pinia中的数据在组件中可以直接修改值,不需要通过mutations。

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"
  // 2.声明
  const store = useStore();


  // 4.修改state中的数据
  const numAdd = () => {
    store.num ++;
  }

</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>name:{{ store.name }}</p>
  <p>num: {{ store.num }}</p>

  <button @click="numAdd">加</button>
</template>

<style scoped>

</style>

七、组件中解构数据进行修改

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"

  // vue提供解构store的方式,将整个stroe中的数据元素全部解构(属性、方法等)
  import {toRefs} from "vue"

  // pinia提供解构store的方式,只解构属性。
  import {storeToRefs} from "pinia"


  // 2.声明
  const store = useStore();


  // 4.解构后修改数据,通过vue提供的方式解构出来的数据,是将整个stroe中的数据元素全部解构(属性、方法等)
  let {name, num} = toRefs(store);

  // 5.通过pinia提供的方式解构,只解构属性。
  // let {name, num} = storeToRefs(store);

  const numAdd = () => {
    num.value ++;
  }

</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>name:{{ name }}</p>
  <p>num: {{ num }}</p>

  <button @click="numAdd">加</button>
</template>

<style scoped>

</style>

八、pinia对数据批量更新

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"

  // pinia提供解构store的方式,只解构属性。
  import {storeToRefs} from "pinia"


  // 2.声明
  const store = useStore();

  let {name, num, arr} = storeToRefs(store);

  const numAdd = () => {
    // 4.批量修改数据
    store.$patch((state) => {
      state.num ++;
      state.name = '张三';
      state.arr.push(4)
    })
    // num.value ++;
  }

</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>name:{{ name }}</p>
  <p>num: {{ num }}</p>
  <p>arr: {{ arr }}</p>

  <button @click="numAdd">加</button>
</template>

<style scoped>

</style>

九、pinia中的getters(Pinia中的getter和Vue中的计算属性几乎一样,在获取State值之前可以做一些逻辑处理。getter中的值有缓存特性,如果值没有改变,多次使用也只会调用一次)

js

复制代码
// 1.引入pinia对象
import {defineStore} from 'pinia';

// 2.创建管理状态仓库
export const useStore = defineStore("store", {
    // 选项式,更接近于vuex
    state: () => {
        return {
            num: 1,
            name: 'gxy',
            arr: [1,2,3]
        }
    },
    getters: {  //getter中不仅可以传递state直接改变数据状态,还可以使用this来改变数据
        // 通过state来获取改变数据
        changeNums(state) {
            return state.num + 5
        },
        // 通过this来获取改变数据
        changeNum() {
            // 由于该方法有缓存机制,所以不管在页面中调用几次,这里只会运行一次(log只会打印一次)。这样大大提高了运行性能。
            console.log('************************');
            return this.num + 5
        }
    },
    actions: {}
})

组件

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"

  // pinia提供解构store的方式,只解构属性。
  import {storeToRefs} from "pinia"


  // 2.声明
  const store = useStore();
  let {name, num, arr, changeNum} = storeToRefs(store);

</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
</template>

<style scoped>

</style>

十、actions的使用

在actions中定义的方法在任务组件中都可以调用

js

复制代码
// 1.引入pinia对象
import {defineStore} from 'pinia';

// 2.创建管理状态仓库
export const useStore = defineStore("store", {
    // 选项式,更接近于vuex
    state: () => {
        return {
            num: 1,
            name: 'gxy',
            arr: [1,2,3]
        }
    },
    getters: {  //getter中不仅可以传递state直接改变数据状态,还可以使用this来改变数据
        
    },
    actions: {
        upData(val) {
            this.num += val
        }
    }
})

组件

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"

  // pinia提供解构store的方式,只解构属性。
  import {storeToRefs} from "pinia"


  // 2.声明
  const store = useStore();
  let {name, num, arr, changeNum} = storeToRefs(store);


  const updata = () => {
    store.upData(200)
  }
</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
  <p>nums: {{ num }}</p>

  <!-- 4.调用actions里的方法来实现更新数据 -->
  <div @click="updata">upDate</div>
</template>

<style scoped>

</style>

十一、Pinia模块互相调用

1.在store中创建一个Shop.js,用于管理店铺数据。

2.在主管理器中引入Shop管理器,通过实例后就可以获取到Shop中的数据了。

复制代码
import {defineStore} from 'pinia';


// 1.导入shop模块
import {useShopStore} from './shop';

export const useStore = defineStore("store", {
    // 选项式,更接近于vuex
    state: () => {
        return {
            num: 1,
            name: 'gxy',
            arr: [1,2,3]
        }
    },
    getters: {  //getter中不仅可以传递state直接改变数据状态,还可以使用this来改变数据

        // 获取shop数据方法
        getShopList() {
            return useShopStore().list;
        }
    },
    actions: {
        upData(val) {
            this.num += val
        }
    }
})

组件

复制代码
<script setup>

  // 1.导入store
  import {useStore} from "../store"

  // pinia提供解构store的方式,只解构属性。
  import {storeToRefs} from "pinia"


  // 2.声明
  const store = useStore();
  let {name, num, arr, getShopList} = storeToRefs(store);


  const updata = () => {
    store.upData(200)
  }
</script>

<template>
  <h1>HelloWorld</h1>

  <!-- 3.展示数据 -->
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
  <p>num: {{ changeNum }}</p>
  <p>nums: {{ num }}</p>


  <!-- 展示shop数据 -->
  <p>shop: {{ getShopList }}</p>

  <!-- 4.调用actions里的方法来实现更新数据 -->
  <div @click="updata">upDate</div>
</template>

<style scoped>

</style>

十二、pinia数据持久化

1.安装插件

npm install pinia-plugin-persist

2.在main.js中挂载该插件

复制代码
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from "pinia"

// 1.导入 pinia持久化插件
import { piniaPluginPersist } from "pinia-plugin-persist"

const pinia = createPinia();

// 2.将插件注册在Pinia中
pinia.use(piniaPluginPersist)

const app = createApp(App);

app.use(pinia);

app.mount('#app');

3.在对应的数据管理器中配置持久化

import {defineStore} from "pinia"

export const useShopStore = defineStore('shop', {

state: () => {

return {

list: ['零食','生鲜'],

price: [12,13]

}

},

getters: {

复制代码
},
actions: {

},
// 使用插件开启数据缓存
persist: {
    enabled: true,
    strategies: [
        {
            // key的名称
            key: "my-shop",
            // 更改默认存储,改为localStorage
            strorage: localStorage,
            // 默认是全部进行存储
            // 可以选择哪些进行local存储,这样就不用全部都进行存储了。
            paths: ["list"],
        }
    ]
}

})

相关推荐
我的心巴1 小时前
vue-print-nb 打印相关问题
前端·vue.js·elementui
coderYYY2 小时前
element树结构el-tree,默认选中当前setCurrentKey无效
前端·javascript·vue.js
程序员秘密基地2 小时前
基于vscode,idea,java,html,css,vue,echart,maven,springboot,mysql数据库,在线考试系统
java·vue.js·spring boot·spring·web app
程序员-小李3 小时前
VuePress完美整合Toast消息提示
前端·javascript·vue.js
萌萌哒草头将军13 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js
ai产品老杨16 小时前
减少交通拥堵、提高效率、改善交通安全的智慧交通开源了。
前端·vue.js·算法·ecmascript·音视频
张老爷子17 小时前
记录uniapp开发安卓使用webRTC实现语音推送
vue.js
发渐稀18 小时前
vue项目引入tailwindcss
前端·javascript·vue.js
vanora111121 小时前
Vue在线预览excel、word、ppt等格式数据。
前端·javascript·vue.js
xiaogg36781 天前
网站首页菜单顶部下拉上下布局以及可关闭标签页实现vue+elementui
javascript·vue.js·elementui