vue stores全局状态共享

目录

一、个人理解

二、安装

三、登录案例


一、个人理解

作为一个后端开发,我个人觉得这个stores性质有点类似于全局变量。相等于后端里的一个全局的字典对象,在后端中,我们需要通过全局变量/对象去判断处理相关逻辑,同样store可以为前端处理达到这种效果,vue的store支持在不同的组件中引入,引入的组件可以访问/设置store对象值,拿到唯一的值。

二、安装

使用npm安装,需要有node环境。

复制代码
npm install vuex

三、登录案例

vue项目中新建stores文件夹,新建UseStore.js文件。

javascript 复制代码
import { defineStore } from "pinia";
import { ref } from "vue";

export const useUserStore = defineStore('userStore', () => {
    const userName = ref('')

    function setUserName(value){
        userName.value = value
    }

    return { userName, setUserName}
})

登录页面组件中,通过引入UseStore.js文件,可以调用useUserStore对象。

bash 复制代码
<template>
pass
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import axios from 'axios';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { useUserStore } from '@/stores/userStore.js';
  
  const store = useUserStore()

  const route = useRoute()
  const router = useRouter()

  const loginParams = reactive({
    'userName': '',
    'password': '',
  })

  const rules = reactive({
    userName: [{required: true, message: '请输入用户名', trigger: 'blur'}],
    password: [{required: true, message: '请输入密码', trigger: 'blur'}]
  })

  const user = ref(null)
  const loading = ref(null)
  const error = ref(null)
  const total = ref(0)


  function userLogin (){
    loading.value = true
    axios.post('http://123:456/login', loginParams)
    .then((res) => {
      # 设置登录用户
      store.setUserName(loginParams.userName)

      // 登录成功跳转页面路由,store.userName获取store变量值
      ElMessage.success(`用户:${store.userName},欢迎回来!`)
      router.push({ name: 'handle'})
    })
    .catch(() => {
      ElMessage.error('用户名或密码错误!')
      loading.value = false
    })
    .finally(() => {
      loading.value = false
    })
  }

<style scoped>
pass
</style>
相关推荐
叫我一声阿雷吧1 天前
JS 入门通关手册(45):浏览器渲染原理与重绘重排(性能优化核心,面试必考
javascript·前端面试·前端性能优化·浏览器渲染·浏览器渲染原理,重排重绘·reflow·repaint
大家的林语冰1 天前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong231 天前
第 8 课:开始引入组合式函数
前端·javascript·学习
田八1 天前
聊聊AI的发展史,AI的爆发并不是偶然
前端·人工智能·程序员
zhanghongbin011 天前
AI 采集器:Claude Code、OpenAI、LiteLLM 监控
java·前端·人工智能
IT_陈寒1 天前
Python的列表推导式里藏了个坑,差点让我加班到凌晨
前端·人工智能·后端
吴声子夜歌1 天前
ES6——正则的扩展详解
前端·mysql·es6
天若有情6731 天前
【C++原创开源】formort.h:一行头文件,实现比JS模板字符串更爽的链式拼接+响应式变量
开发语言·javascript·c++·git·github·开源项目·模版字符串
天***88521 天前
Edge 浏览器离线绿色增强版+官方安装包,支持win7等系统
前端·edge
漫游的渔夫1 天前
别再直接 `json.loads` 了!AI 返回的 JSON 坑位指南
前端·人工智能