vue-cli学习笔记 03、Vuex(数据存储方案)(二)

简介: vue-cli学习笔记 03、Vuex(数据存储方案)(二)

三、VueX基本使用操作(使用Composition API)


说明:这里演示使用Composition API来进行store全局变量的取值与修改操作。


xxx.vue:核心,取值与发送修改指令都在setup()中执行。


<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <h1>store.name=>{{ name }}</h1>
    <button @click="handleClick('liner')">修改store.name=>liner</button>
  </div>
</template>
<script>
// 引入toRefs、useStore函数
import { toRefs } from "vue";
import { useStore } from "vuex";
export default {
  name: "Home",
  components: {},
  setup() {
    const store = useStore(); //取到store全局对象
    // 1、取全局变量操作
    const { name } = toRefs(store.state); // 从store中拿取到state全局对象,并进行解构赋值
    // 2、发送指令修改全局变量操作
    const handleClick = () => {
      store.dispatch("change", "liner");
    };
    return { handleClick, name };
  },
};
</script>



index.js


import { createStore } from 'vuex'
export default createStore({
  state: {
    name: "changlu"
  },
  mutations: {
    change(state, str) {
      state.name = str;
    }
  },
  actions: {
    change(store, str) {
      setTimeout(() => {
        store.commit("change", str);
      }, 2000);
    }
  },
  modules: {
  }
})





四、vue-cli中使用vuex


若是我们想要将一些变量值进行全局管理,此时我们可以使用vuex。


第一步:


npm install vuex --save


第二步:




首先是store/modules.user.js:可以表示单个vuex对象(user)


const user = {
  state: {  // 定义了两个变量
    isLogin: false,
    userId: '123456'
  },
  mutations: {
    SET_USERID: (state, userId) => {
      state.token = userId
    },
    SET_ISLOGIN: (state, isLogin) => {
      state.token = isLogin
    }
  },
  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      console.log('userInfo=>', userInfo)
      return new Promise((resolve, reject) => {
        loginApi.login(userInfo).then((result) => {
          console.log('result=>', result)
          if (result.code === 200) {
            commit('SET_ISLOGIN', true) // 标识是否登陆成功
            commit('SET_USERID', result.result) // 添加用户id
          }
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
export default user



store/getters.js:用于直接快速取到某个vuex对象值


const getters = {
  userId: state => state.user.userId
}
export default getters


store/index.js:创建vuex对象,引入vuex对象以及getters


import Vue from 'vue'
import Vuex from 'vuex'
// 可直接取值
import getters from './getters'
// 单个文件引入
import user from './modules/user'
Vue.use(Vuex)  // 使用vuex插件
const store = new Vuex.Store({
  modules: {   // 若是有多个vuex对象就统一在这里载入
    user
  },
  getters  // 这里是载入getters对象
})
export default store



最后当然是将创建好的store对象直接挂载到vue对象上!也就是main.js:


import store from './store' // 引入store对象
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>',
  store  //这里来插入store对象
})


第三步:定义好vuex对象,那当然是使用了


//取值:
//①通过vuex对象来取出属性值(可直接取)
this.$store.state.user.userId   //取到user对象里的
//②直接通过getters来取出
this.$store.getters.userId
//修改值:需要经过action->mutations来进行取值,action统一进行异步操作,mutations来进行同步操作(规范)
handleLogin (auto = false) {
    //登陆调用vuex中方法
    this.$store.dispatch('Login', this.loginForm).then((result) => {
        if (result.code === 200) {
            if (!auto) {
                this.$message({
                    showClose: true,
                    message: '登陆成功!',
                    type: 'success'
                })
            }
            // 记住我 存储到cookie用户名、密码7天
            if (this.remember) {
                Cookies.set('username', this.loginForm.username, { expires: 7 })
                Cookies.set('password', this.loginForm.password, { expires: 7 })
            }
            this.$router.push({ name: 'Commit', params: { userId: result.result } })
        } else {
            this.$message({
                showClose: true,
                message: result.message + ',登陆失败!',
                type: 'error'
            })
        }
    })
}


相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8077 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10262 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1546 5
|
9天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2696 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2376 0