说明
修改全局状态变量的值,是一个比较常规而且常见的操作。
本文就介绍四种常见的操作。
由于option store
和setup store
在修改的时候略有不同,所以本文也会将不同点体现一下。
全局状态变量的定义
包含了 option store
和setup store
两种定义方式;
在下面的修改操作中会根据这两种不同的定义来分别阐述。
// 导入 definestore api import { definestore } from 'pinia' // 导入 reactive 依赖 import { reactive } from 'vue' // 定义全局状态方式一 : option store export const useclassstore = definestore('classinfo',{ state: () => ({ name:'快乐篮球二班', studentnum:30 }), actions:{ // 用来更新状态的值 updatename(){ this.name = '使用actions修改的name' } } }) // 定义全局状态方式二 : setup store export const usestudentstore = definestore('studentinfo',() => { // 响应式状态 const student = reactive({ name : '小明', age:12, classname:'快乐足球一班' }) // 直接定义一个方法进行数据属性的修改 const updatename = (namep:string)=>{ student.name = namep } return { student,updatename } })
方式一:直接修改
直接修改 : 就是直接读取对象进行变量值的替换。
option store
// 导入全局状态变量的定义 import { useclassstore } from './storea' // 获取全局状态变量的对象 const classstore = useclassstore() // 方式一 : 直接修改 classstore.studentnum = 36
setup store
// 导入全局状态变量的定义 import { usestudentstore } from './storea' // 获取全局状态变量的对象 const studentstore = usestudentstore() // 方式一 : 直接修改 studentstore.student.classname = '我也不知道是哪个班的'
方式二:$patch 方式修改
参数是一个对象的形式
option store
直接放入 【参数对象】 : {key:value}
就ok了
// 导入全局状态变量的定义 import { useclassstore } from './storea' // 获取全局状态变量的对象 const classstore = useclassstore() // 方式二 : $patch 方法修改 classstore.$patch({studentnum:20})
setup store
由于 状态变量在定义的时候,就是一个响应式对象,所以需要把整个的对象都放进去才ok。
// 导入全局状态变量的定义 import { usestudentstore } from './storea' // 获取全局状态变量的对象 const studentstore = usestudentstore() // 方式二 : $patch 方法修改 studentstore.$patch({student:{ name: studentstore.student.name, age: studentstore.student.age, classname:'又换了一个班级' }})
方式三:$patch 带参数的方式修改
参数是 函数
的形式,且函数的参数就是 原state对象
这种方式用起来比【方式二】要更加灵活。
option store
// 导入全局状态变量的定义 import { useclassstore } from './storea' // 获取全局状态变量的对象 const classstore = useclassstore() // 方式三 :$patch + 函数参数的方法修改 : 函数的参数就是 状态对象 classstore.$patch((state)=>{ console.log(state) state.studentnum = 100 })
setup store
// 导入全局状态变量的定义 import { usestudentstore } from './storea' // 获取全局状态变量的对象 const studentstore = usestudentstore() // 方式三 :$patch + 函数参数的方法修改 : 函数的参数就是 状态对象 studentstore.$patch((state)=>{ console.log(state) state.student.classname = '超级无敌快乐踢足球的班' })
方式四:actions方法的方式进行修改
这种方式比较好理解,就是通过调用已经定义好的方法的方式来进行变量值的修改。
也比较推荐使用这一种方式。
option store
// 导入全局状态变量的定义 import { useclassstore } from './storea' // 获取全局状态变量的对象 const classstore = useclassstore() // 方式四 :actions 方法的方式进行数据的修改 classstore.updatename()
setup store
// 导入全局状态变量的定义 import { usestudentstore } from './storea' // 获取全局状态变量的对象 const studentstore = usestudentstore() // 方式四 :actions 方法的方式进行数据的修改 studentstore.updatename('小红')
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论