Vue3 uses repository Pinia (actions)

1. Create actions in store.js

import {
    
     defineStore } from "pinia";
export const useStore = defineStore('main', {
    
    
    state() {
    
     // state表示这个store里的状态,也就是存放数据的地方
        return {
    
    
            name: '张三',
            age:'26' 
        }
    },
    actions: {
    
      // actions 相当于组件中的 methods
        updateAge(data) {
    
    
          this.age = data // 可以使用this访问和修改state中的数据
        },
    },
})

2. Reference store.js

import {
    
    useStore} from "../store/store" // 引入store
const store = useStore()

3. Click to modify the value in state

1. Single modification

const edit = ()=>{
    
    
	store.updateAge("32")
}

2. Batch modification

const edit = ()=>{
    
            
    store.$patch({
    
    
         name:"李四",
         age:"32"
    })
}

4. Effect

insert image description here

おすすめ

転載: blog.csdn.net/qq_37332614/article/details/131722940