- 决定了使用pinia 而不是 vuex, pinia官网:https://pinia.web3doc.top/
- 终端:npm install pinia
- 在 src 目录下, 新建store 文件夹, index.ts 文件
- index.ts 中代码
import { defineStore } from 'pinia'
export const mainStore = defineStore('main', {
state: () => {
return {
msg: '无',
count: 1,
phone: '13411118888'
}
},
getters: {
phoneHide (state) {
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
},
actions: {}
})
- 在main.ts中
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
import { createPinia } from 'pinia'
createApp(App)
.use(router)
.use(createPinia())
.mount('#app')
- 在login 文件下 indexName.vue 中
<template>
<div>登录</div>
<div>
<h5>store.count: {{ store.count }}</h5>
<h5>store.msg: {{ store.msg }}</h5>
<h5>store.phone: {{ store.phone }}</h5>
</div>
<hr>
<div>
<h5>{{ count }}</h5>
<h5>{{ msg }}</h5>
<h5>{{ phoneHide }}</h5>
</div>
<div>
<button @click="add">
count 加一
</button>
<hr>
<button @click="onPhoneHide">
改变电话
</button>
</div>
</template>
<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { mainStore } from '../../store/index.ts'
const store = mainStore()
const { count, msg, phoneHide } = storeToRefs(store)
const add = () => {
store.$patch({
count: store.count + 1,
msg: store.msg + 'hi'
})
}
const onPhoneHide = () => {
store.$patch({
phone: 15588883333
})
}
</script>
- 终端: npm run dev