1.安装
npm install pinia
2.挂载到main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'
// 创建pinia 实例
const pinia = createPinia()
createApp(App).use(router).use(pinia).mount('#app')
3.在页面中引入
<template>
<div class="hello">
<h2 class="">{{ helloWorld }}</h2>
<h2 class="">{{ count }}</h2>
<h2 class="">电话号码:{{ phoneHidden }}</h2>
<button @click="handleClick">点击增加</button>
<!-- 多条数据同时更新状态数据,推荐使用$patch方式更新。 -->
<button @click="handleClickPatch">修改数据($patch)</button>
<button @click="handleClickMethod">修改数据($patch+函数)</button>
<button @click="handleClickActions">修改数据(actions)</button>
<div>
{{ store.listArray }}
<button @click="getList">显示List</button>
</div>
</div>
</template>
<script setup>
import { mainStore } from "../store/index";
// 变成响应式
import { storeToRefs } from 'pinia'
const store = mainStore();
const { helloWorld, count, phoneHidden } = storeToRefs(store);
const handleClick = () => {
store.count++;
store.helloWorld = store.helloWorld === "我变了" ? "HelloWorld" : "我变了";
};
const handleClickPatch = () => {
store.$patch({
count: store.count + 2
});
};
const handleClickMethod = () => {
store.$patch((state) => {
console.log('state', state)
state.count++;
});
};
const handleClickActions = () => {
store.changeState()
}
const getList = () => {
store.getList();
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
3.在store下创建index.js
import { defineStore } from 'pinia'
import { userStore } from './user.js'
export const mainStore = defineStore('main', {
state: () => {
return {
helloWorld: "helloWorld",
count: 0,
phone: '13120907614',
listArray: userStore().list
}
},
getters: {
phoneHidden(state) {
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
},
},
actions: {
// 在用actions的时候,不能使用箭头函数,因为箭头函数绑定是外部的this
changeState() {
this.count++
this.helloWorld = '通过action改变'
},
getList(){
console.log(userStore().list)
}
}
})
4.user.js
import { defineStore } from 'pinia'
export const userStore = defineStore('user', {
state: () => {
return {
list: ['小红', '小美', '小红']
}
},
getters: {
phoneHidden(state) {
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
},
actions: {
}
})