vue3项目,vite+vue3+ts+pinia(4)-共享状态pinia

  1. 决定了使用pinia 而不是 vuex, pinia官网:https://pinia.web3doc.top/
  2. 终端:npm install pinia
    在这里插入图片描述
  3. 在 src 目录下, 新建store 文件夹, index.ts 文件 在这里插入图片描述
  4. 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')
    }
  },
  // 修改state全局状态
  actions: {}
})

  1. 在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')
  1. 在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 } = store // 发现没有响应式

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>

  1. 终端: npm run dev
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值