pinia
- 状态管理器,统一状态管理,组件间通信
- state、getter 和 action,我们可以假设这些概念相当于组件中的 data、 computed 和 methods
1 安装
npm install pinia
2 在store/xx.js,写入代码,可以定义多个
import {defineStore} from "pinia";
export const useCountStore=defineStore('counter',{
// 定义变量
state:()=>{
return{count:0}
},
// 这里面写方法,与后端交互或逻辑判断,再操作数据
actions:{
addcounnter(){
this.count++
}
}
})
// getter-->获取数据
getters: {
getCount(){
return this.count
},
},
3 main.js中使用插件
import {createPinia} from "pinia";
let pinia=createPinia()
createApp(App).use(pinia).mount('#app')
4 在组件中使用pinia的数据
<template>
<h1>ddddd</h1>
<h2>{{counter.count}}</h2>
</template>
<script setup>
import {useCountStore} from "../store/counter";
let counter = useCountStore()
</script>
5 getters用法
- 按价格过滤
- 无参
import {defineStore} from "pinia";
export const usebookStore = defineStore("book", {
state: () => {
return {
data: [],
};
},
getters: {
suds: (state) => state.data.filter((book) => book.price > 200)
}
});
<template>
<div v-for="i in book.suds">
<p>{{i.name}}----{{i.price}}---{{i.publish}} </p>
</div>
</template>
<script setup>
import {usebookStore} from "../store/bookdata";
import axios from "axios";
let book = usebookStore()
async function fetchData() {
try {
const response = await axios.get("http://127.0.0.1:8000/app01/");
book.data = response.data;
} catch (error) {
console.log(error);
}
}
fetchData()
</script>
-
有参
-
在 Vue 的 Store 中,getter 本身是没有传参的。Getter 是根据 Store 的状态属性进行计算的,它们是无参数的计算属性。
然而,你可以通过 getter 返回一个函数,来实现传递参数的效果。这样,你可以在组件中使用该 getter 函数,并传递参数给它。
import {defineStore} from "pinia";
export const usebookStore = defineStore("book", {
state: () => {
return {
data: [],
};
},
getters: {
sudss: (state)=> (num) => state.data.filter((book) => book.price > num)
}
});
<template>
<div v-for="i in book.sudss(num)">
<p>{{i.name}}----{{i.price}}---{{i.publish}}</p>
</div>
<input type="text" v-model="num">
</template>
<script setup>
import {usebookStore} from "../store/bookdata";
import axios from "axios";
import {ref} from 'vue'
let book = usebookStore()
let num=ref(0)
async function fetchData() {
try {
const response = await axios.get("http://127.0.0.1:8000/app01/");
book.data = response.data;
} catch (error) {
console.log(error);
}
}
fetchData()
</script>
标签:usebookStore,state,book,pinia,vue3,import,data
From: https://www.cnblogs.com/unrealqcc/p/18194584