state

import { defineStore } from 'pinia'
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useStore = defineStore('main', {
    state:()=> {
        return {
            name: 'zs',
            age: 18
        }
    },
    getters: {

    },
    actions: {
        setName(name:string) {
            this.name = name
        }
    }
})


<template>
  <div>
    {{ user.name }}----{{ user.age }}
    <button @click="change">改变值</button>
  </div>
</template>

<script setup lang="ts">
import { useStore } from "./store";

const user = useStore();

// 第一种方式修改state
/* const change = () => {
  useStore.name = '小黑'
} */

// 第二种方式 调用 $patch 方法,可以修改多个数据
/* const change = () => {
  user.$patch({
    name: "小黑",
    age: 20,
  });
}; */

// 第三种方式 $patch 方法也接受一个函数来批量修改
/* const change = () => {
  user.$patch((state)=>{
    state.name = '小黑'
    state.age = 20
  })
}; */

// 第四种方式 可以通过将其 $state 属性设置为新对象来替换 Store 的整个状态
/* const change = () => {
  user.$state = {
    name: '小黑',
    age: 20
  }
}; */

// 第五种 使用 actions
const change = () => {
  user.setName('小黑')
};


</script>

<style scoped></style>

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐