(九)使用 Actions 来修改状态
状态 使用 修改 Actions
2023-06-13 09:17:09 时间
一、使用 Actions
修改状态
说明
- 为什么需要
actions
呢,我们明明可以在组件中直接修改store
里面的数据 - 原因就是他和
getters
是一样的,为了复用,同样的逻辑只用触发actions
就可以修改了
二、如何在 pinia
定义 actions
store.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useNoteStore = defineStore('note', () => {
const noteList = ref([
{
title: '标题1',
desc: '详情内容1'
}
])
/**
* 定义一个保存搜索词的响应的 ref ,并使用 getters
*/
const searchText = ref('')
const searchNotes = computed(() => {
// 如果搜索框为 空 就展示所有 noteList
if(searchText.vaue === '') {
return noteList
} else {
return noteList.value.filter(note => {
return noteList.title.includes(state.searchText)
})
}
})
/**
* 使用 actions
*/
function addNote(title, desc) {
noteList.value.push({
title: '标题x',
desc: '详情内容x'
})
searchText: ''
}
return {
noteList, // state 数据
searchText, // 搜索框内容
searchNotes, // 过滤过后的计算属性
addNote, // actions
}
})
三、在组件中使用
<template>
<div>{{newNoteList.searchNotes}}</div>
</template>
<script setup>
import { useNoteStore } from '@/store/note.js'
const noteList = ref([
{
title: '标题1',
desc: '详情内容1'
}
])
// 把返回值放到一个新的变量里面
const noteStore = useNoteStore()
functions addNote() {
noteStore.addNote(noteList.title, noteList.desc)
// 通过 actions 就不用手动去修改了,直接去调用 actions 传值就可以了
// noteStore.$patch({
// notes: [
// ...noteStore.noteList,
// {
// title: '标题',
// desc: '详细内容'
// }
// ],
// searchText: ''
// })
}
</script>
相关文章
- Fabric.js 使用纯色遮挡画布(前景色)
- 使用 WGCLOUD 监测SQL Server数据库状态
- 【说站】Vuex中状态管理器的使用详解
- Http常见的状态码
- Android监听来电状态
- 2023-01-12:一个n*n的二维数组中,只有0和1两种值, 当你决定在某个位置操作一次, 那么该位置的行和列整体都会变成1,不管之前是什么状态。 返回让所
- pytest学习和使用14-Pytest用例执行结果有哪几种状态?
- 使用Prometheus联动Grafana监控kubernetes集群状态
- 系统使用状况使用Linux查看磁盘文件系统的状态(查看linux磁盘文件)
- MySQL Status Performance_schema_stage_classes_lost 数据库状态作用意思及如何正确
- MySQL Status Ssl_version 数据库状态作用意思及如何正确
- Linux查看Oracle服务器启动状态(linux查看oracle是否启动)
- 使用Redis进行状态检测(redis检测)
- Linux下查看进程状态的方法(linux 查看进程状态)
- 使用命令检查Redis服务器的运行状态(检查redis状态命令)
- 使用CMD命令查看MySQL状态(cmd看mysql)
- 如何在未登录状态下使用Redis(未登录怎么使用redis)
- 使用SSH远程查看Redis状态(ssh查看redis)
- 判断Redis连接状态探查是否一切就绪(判断是否连上redis)
- 关于WPF使用MultiConverter控制Button状态的详细介绍
- 使用JavaScript获取电池状态的方法