Vue3:状态管理-Store(Vuex,Pinia)
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                
// 安装Pinia
npm install pinia
 
// 在main.js中引入并使用Pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
 
const app = createApp(App)
const pinia = createPinia()
 
app.use(pinia)
app.mount('#app')
 
// 创建一个store.js,用于定义和管理应用状态
import { defineStore } from 'pinia'
 
export const useCounterStore = defineStore({
  id: 'counter',
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
})
 
// 在Vue组件中使用store
<template>
  <div>{{ counterStore.count }}</div>
  <button @click="counterStore.increment">增加</button>
</template>
 
<script setup>
import { useCounterStore } from './store'
 
const counterStore = useCounterStore()
</script>这个例子展示了如何在Vue 3应用中使用Pinia来管理状态。首先,我们安装Pinia并在入口文件main.js中引用它。然后,我们创建一个store.js文件,定义了一个名为counter的store,包含一个状态count和一个行为increment。最后,在Vue组件中,我们通过setup语法糖使用store,并展示了如何读取count值和调用increment方法。
评论已关闭