前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(八)使用 $patch 同时修改多个状态

(八)使用 $patch 同时修改多个状态

作者头像
老怪兽
发布2023-02-22 15:43:05
5450
发布2023-02-22 15:43:05
举报
文章被收录于专栏:老怪兽的前端之旅

一、使用 $patch 同时修改多个状态

  • store.js
代码语言:javascript
复制
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.value === '') {
            return noteList
        } else {
            return noteList.value.filter(note => {
                return noteList.title.includes(state.searchText)
            })
        }
    })

    return {
        noteList,           // state 数据
        searchText,         // 搜索框内容
        searchNotes,        // 过滤过后的计算属性
    }
})
  • 在组件中同时修改多个 state
代码语言:javascript
复制
<template>
    <div>{{newNoteList.searchNotes}}</div>
</template>

<script setup>
import { useNoteStore } from '@/store/note.js'

// 把返回值放到一个新的变量里面
const noteStore = useNoteStore()

functions addNote() {
    noteStore.$patch({
        notes: [
            ...noteStore.noteList,
            {
                title: '标题',
                desc: '详细内容'
            }
        ],
        searchText: ''
    })
}
</script>

总结-写在最后

总计

$patch 是一个对象,里面修改的就是 store 当中 state 的状态了

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年11月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、使用 $patch 同时修改多个状态
  • 总结-写在最后
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档