Pinia的安装和引入
1.安装Pinia
npm install pinia
2. 在vue项目的main.js文件中引入pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)app.use(pinia)
app.mount('#app')
Pinia的基本使用
使用pinia实现计数器
1.在src目录下创建stores目录,并新建文件counter.js
**2. 在counter.js文件中使用defineStore定义对象useCounterStore **
import { defineStore } from 'pinia'
import { ref } from 'vue'export const useCounterStore = defineStore('counter', () => {// 定义数据(state)const count = ref(0)// 定义修改数据的方法(action 同步+异步)const increment = () => {count.value++}// 以对象的方式return供组件使用return {count,increment}
})
**3.在App.vue文件中导入counter.js文件中的useCounterStore **
<script setup>
// 1. 导入use打头的方法
import { useCounterStore } from '@/stores/counter'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore)
</script><template><button @click="counterStore.increment"> {{ counterStore.count}} </button>
</template><style scoped></style>
getters和异步action
在counter.js文件中进行如下定义
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import axios from 'axios'const API_URL = "http://geek.itheima.net/v1_0/channels"
export const useCounterStore = defineStore('counter', () => {// 定义数据(state)const count = ref(0)// 定义修改数据的方法(action 同步+异步)const increment = () => {count.value++}// getter定义const doubleCount = computed(() => count.value * 2)// 定义异步actionconst list = ref([])const getList = async () => {const res = await axios.get(API_URL)list.value = res.data.data.channels}// 以对象的方式return供组件使用return {count,doubleCount,increment,list,getList}
})
在App.vue中使用
<script setup>
// 1. 导入use打头的方法
import { useCounterStore } from '@/stores/counter'
import { onMounted } from 'vue';
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore)
onMounted(()=>{ // 挂载期发起请求counterStore.getList()
})
</script><template><button @click="counterStore.increment"> {{ counterStore.count}} </button>{{ counterStore.doubleCount }}<ul><li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li></ul>
</template><style scoped></style>
使用storeToRefs进行结构赋值,保持响应式更新
<script setup>
// 1. 导入use打头的方法
import { useCounterStore } from '@/stores/counter'
import { onMounted } from 'vue';
import { storeToRefs } from 'pinia'
// 2. 执行方法得到store实例对象
const counterStore = useCounterStore()
console.log(counterStore)// 直接结构赋值(响应式丢失)
// const { count, doubleCount} = counterStore
// console.log(count, doubleCount)// 方法包裹(保持响应式更新)
const { count, doubleCount } = storeToRefs(counterStore)
console.log(count, doubleCount)// 方法直接从原来的counterStore解构赋值
const { increment } = counterStore// 触发action
onMounted(()=>{ counterStore.getList()
})
</script><template><button @click="increment"> {{ count }} </button>{{ doubleCount }}<ul><li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li></ul>
</template><style scoped></style>