vite vue3 配置pinia

准备

https://blog.csdn.net/qq_36437991/article/details/134474050

安装pinia

官网

yarn add pinia

vite vue3 配置pinia_第1张图片
src下新建store文件夹,该文件夹下新建index.ts

import { createPinia } from "pinia";
const store = createPinia();
export default store;

修改main.ts

import { createApp } from "vue";
import App from "./App.vue";
import store from "./store/index";

const app = createApp(App);
app.use(store);
app.mount("#app");

vite vue3 配置pinia_第2张图片

sotre下新建user.ts

import { defineStore } from "pinia";

export const useUserStore = defineStore({
  id: "user", // id必填,且需要唯一
  state: () => {
    return {
      name: "张三",
    };
  },
  actions: {
    updateName(name: string) {
      this.name = name;
    },
  },
});

修改home.vue

<script lang="ts" setup>
import { useUserStore } from '../store/user'
const userStore = useUserStore()
const changeState = () => {
    userStore.updateName('李四')
}
script>
<template>
    <p>获取pinia数据p>
    <div>{{ userStore.name }}div>
    <button @click="changeState">修改statebutton>
template>

vite vue3 配置pinia_第3张图片
vite vue3 配置pinia_第4张图片

你可能感兴趣的:(vue,js,javascript,开发语言,ecmascript)