北京建设局网站首页,网站空间维护,在线咨询 1 网站宣传,wordpress编码学习vue3#xff0c;都会从基础知识点学起。了解setup函数#xff0c;ref#xff0c;recative#xff0c;watch、computed、pinia等如何使用
今天说vue3组合式api#xff0c;pinia
戳这里#xff0c;跳转pinia中文文档
官网的基础示例中提供了三种写法 1、选择式api都会从基础知识点学起。了解setup函数refrecativewatch、computed、pinia等如何使用
今天说vue3组合式apipinia
戳这里跳转pinia中文文档
官网的基础示例中提供了三种写法 1、选择式api类似于vuex的写法 2、组合式apivue3 组合式api写法 3、借助辅助函数mapStores()、mapState() 或 mapActions()
本文主要讲第二种写法它与vue3的语法风格是统一的
使用 1、定义store(stateactiongetters) //defineStore函数创建store实例对象 //defineStore函数需要传递两个参数第一个参数:小仓库名字(唯一id不可重复 用于区分是哪个store这样就不会出现命名冲突组件中使用仓库数据是通过定义变量(useCounterStore )接收defineStore方法返回的函数和仓库名(counter)没有直接关系) //第二个参数:小仓库配置对象 //defineStore方法执行会返回一个函数,函数作用就是让组件可以获取到仓库数据
import {defineStore} from pinia
import {ref} from vue
import axios from axiosexport const useCounterStore defineStore(counter,(){
//数据(state)
const count ref(0)
const API_URL /api/booklist
cosnt list ref([])//getter
const deoubleCount computed(()count.value*2)//修改数据的方法
//(同步action)
const increment (){
count.value
}
//(异步action,与组件中定义数据和方法的风格完全一致)
const loadList async (){
const res await axios.get(API_URL)
list.value res.data
}
//以对象形式返回
return {count,increment,deoubleCount,list,loadList }
})2、组件使用store
script setup
//1、导入useCounterStore 方法
import {useCounterStore } from /stores/counter//2、执行方法得到counterStore对象
const counterStore useCounterStore ()console.log(counterStore)//counterStore 对象包含的就是counter仓库中return出来的对象onMounted((){
counterStore.loadList()
})/scripttemplatebutton clickcounterStore.increment {{counterStore.count}}{{counterStore.deoubleCount }}/buttonul
li v-foritem in counterStore.list :keyitem.id)
{{item.name}}
/li
/ul/template打印counterStore
storeToRefs
为什么要使用storeToRefs可以简化写法原先的counterStore.count通过解构可以直接使用count。中文文档中特意注明不能直接对store进行解构会破坏响应式。响应式丢失视图也不再更新。所以使用storeToRefs函数可以辅助保持数据stategetter的响应式解构 有效写法 观察下区别错误写法下打印countdeoubleCount 拿到的是两个0 正确写法下打印countdeoubleCount 拿到的是两个响应式的对象 方法不需要通过storeToRefs函数解构赋值直接从原来的counterStore中解构赋值
const {increment } counterStore