黑马前端Vue新一代状态管理插件Pinia快速入门视频教程
Pinia主页
超级简单,不需要耐心
npm install pinia
import { createPinia } from 'pinia'
app.use(createPinia())
.js文件pinia的使用和在setup中写的代码基本一致,记得`ruturn`数据就行
// path:@/stores/counter.js
import {computed, ref} from "vue";
import {defineStore} from 'pinia'
// 第一个参数是 store 的唯一标识id
export const useCounterStore = defineStore('counter',()=>{
// VueX:state,数据
const count = ref(0)
// VueX:getters,计算属性
const doubleCount = computed(() => count.value * 2)
// VueX:actions + mutations,方法
function increment(){
count.value++
}
return { count, doubleCount, increment }
})
在vue中导入pinia后需要**赋值操作**,然后使用`.`来访问pinai中的数据和方法
App.vue
<template>
计数器:{{countStore.count}}<br>
加倍计数器:{{countStore.doubleCount}}<br>
<button @click="countStore.increment">点我加1button>
template>
<script setup>
// 引入stroe文件
import {useCounterStore} from "@/stores/counter"
const countStore = useCounterStore()
script>
countStore.去访问store中的数据和方法<template>
计数器:{{count}}<br>
加倍计数器:{{doubleCount}}<br>
<button @click="increment">点我加1button>
template>
<script setup>
import {useCounterStore} from "@/stores/counter"
import {storeToRefs} from "pinia";
// 得到store的实例对象
const countStore = useCounterStore()
// 对state的解构需要使用storeToRefs方法
const { count, doubleCount } = storeToRefs(countStore)
// 对action的结构,直接干
const {increment} = countStore
script>
npm : npm i pinia-plugin-persistedstate
main.js中pinia使用插件import { createApp } from 'vue'
import App from './App.vue'
import { createPinia} from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia() // 创建pinia实例
pinia.use(piniaPluginPersistedstate) // pinia使用持久化插件
createApp(App).use(pinia).mount('#app')

查看保存在localstorage中的结果

只需要给persist加个对象,paths中是要保存的数据的名字
persist: {
storage: sessionStorage,
paths:['count']
}


