vuex3入门

embedded/2024/10/23 22:53:11/

vue2 对应的 vuex、vue-router 都为3.

项目创建与框架安装

vue create hellovuex3

npm i vuex@3

npm install

npm run serve

请添加图片描述

vuex使用

vue集成vuex,数据更新&展示

  1. 新建store/index.js
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {score: 0},mutations: {increment(state, value) {state.score += value}},modules: {}
})
export default store;

state 相当于普通组件data,读写数据的句柄。

mutations 相当于普通组件的methods, 封装同步修改state属性的方法

  1. 将vuex实例与vue实例进行绑定
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";Vue.config.productionTip = falsenew Vue({store,render: h => h(App),
}).$mount('#app')
  1. 修改HelloWorld组件 展示和修改score
<template><div class="hello"><h1>{{ msg }}</h1><div>score: {{ $store.state.score }}</div><button @click="$store.commit('increment', 2)">score+2</button></div>
</template>

访问数据 this.$store.state.score
函数调用 this.$store.commit(key,val)

请添加图片描述

存在的问题:vuex存储数据不是持久化存储,刷新页面后,数据会消失。

  1. 处理vuex处理刷新后数据消失问题
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)const store = new Vuex.Store({state: {// score:0,score: localStorage.getItem('score') ? localStorage.getItem('score') : 0},mutations: {increment(state, value) {state.score += valuelocalStorage.setItem('score', state.score)}},modules: {}
})
export default store;

vuex数据的异步修改

vuex同步函数在mutations中进行定义,异步修改需要定义到actions.

    mutations: {increment(state, value) {state.score += valuelocalStorage.setItem('score', state.score)},setScore(state, value) {state.score = valuelocalStorage.setItem('score', state.score)}},actions: {setDataAsync({commit}, value) {setTimeout(() => commit('setScore', value), 3000)}},
<template><div class="hello"><h1>{{ msg }}</h1><div>score: {{ $store.state.score }}</div><button @click="$store.commit('increment', 2)">score+2</button><button @click="$store.dispatch('setDataAsync', 5)">异步修改score为5</button></div>
</template>

异步函数调用 this.$store.dispatch(key,val);

计算属性getter

   getters: {computedScore(state) {console.error('computedScore is called')return state.score}},modules: {}
})

getter和computed功能上是一致,对计算结果进行缓存

<template><div class="hello"><h1>{{ msg }}</h1><div>score: {{ $store.state.score }}</div><button @click="$store.commit('increment', 2)">score+2</button><button @click="$store.dispatch('setDataAsync', 5)">异步修改score为5</button><button @click=" score = $store.getters.computedScore">通过getter读取score {{ score }}</button></div>
</template><script>
export default {name: 'HelloWorld',data() {return {score: 0,}},

连续点击getter读取按钮, computedScore is called 只会执行一次; 只有当score变化之后,才会进行调用。
访问方式:this.$store.getters.computedScore

modules

上面的例子仅仅维护了一个字段score,生产环境碰到的会是多种类型的、eg. 用户管理、订单管理…, 这个时候分模块就显得很有必要了.

  1. 创建store/modules/user.js
const user = {state: {token: localStorage.getItem('token')},mutations: {setToken(state, token) {state.token = tokenlocalStorage.setItem('token', token)},},getters: {token(state) {return state.token.repeat(2)}},
}
export default user;

注意:

1.这里面的state写法与以往 state(){return{}}不同.

2.需要将数据类型进行导出 export default user;

  1. store/index.js 添加 modules属性
import user from "@/store/modules/user";
const store = new Vuex.Store({...modules: {user},
  1. 进行调用测试
  mounted() {this.$store.commit('setToken', 'tokenxxx')  //调用方法设置数据没有模块限定名console.error(this.$store.state.user.token) //state读取 , 前面添加module名限定console.error(this.$store.getters.token) //直接去掉了 module}

调用模块内的方法有些区别

  1. mutations、actions方法、getter不能携带module
  2. state要携带module

其他

  1. 国内github不稳定处理办法 测试采用配置 C:\Windows\System32\drivers\etc\hosts 域名和ip映射可行。
  2. package.json scripts 标签定义了 npm 、yarn可以执行的命令
  3. pakcage-lock.json 存储了npm install时框架依赖情况;yarn-lock.json 存储了 yarn install时框架依赖情况
  4. npm i --legacy-peer-deps
    // 使用 npm i --legacy-peer-deps 命令安装依赖时,会忽略 peer dependencies 的版本冲突问题。

  5. vue2 devtool chrome 插件下载
  6. eslint 报错

根路径下创建.eslintrc.js文件,其内容如下:

module.exports = {'parser': '@babel/eslint-parser',  //支持ES6语法rules: {"*": "off"},
};

/vue.config.js 添加 lintOnSave:false

const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,lintOnSave: false,
})
  1. 视频推荐 - 30分钟学会Vue之VueRouter&Vuex

http://www.ppmy.cn/embedded/129925.html

相关文章

IT运维的365天--017 如何在两台Linux服务器之间快速批量传输文件夹(同时设置免密)

前情提要(两台Linux服务器之间传输批量文件夹): 两台都是外网服务器,都是Linux系统(CentOS),都安装了宝塔,用于搭建巨量的静态网站,由于A服务器准备不要了,所以要在A服务器转移几百个静态网站到B服务器。 Linux下scp单命令传输文件夹测试: 准备工作,先测试转移一…

Cursor零基础小白教程系列 - 开卷有益

最适合小白零基础的Cursor教程 网站lookai.top相同作者&#xff0c;最新文章会在网站更新&#xff0c;欢迎收藏书签 写在前面的话 Cursor在我看来 我认为当下AI时代&#xff0c;Cursor能够极大赋能每个普通人&#xff0c;帮助每个普通人实现自己的创意和想法。 例子&#xff…

Flink时间窗口程序骨架结构

前言 Flink 作业的基本骨架结构包含三部分&#xff1a;创建执行环境、定义数据处理逻辑、提交并执行Flink作业。 日常大部分 Flink 作业是基于时间窗口计算模型的&#xff0c;同样的&#xff0c;开发一个Flink时间窗口作业也有一套基本的骨架结构&#xff0c;了解这套结构有助…

【C++刷题】力扣-#268-丢失的数字

题目描述 给定一个包含从 1 到 n 的整数的数组 nums&#xff0c;其中 n 是数组的长度。数组中的元素都不相同&#xff0c;但是缺失了一个数字&#xff0c;导致数组和为 n*(n1)/2 减去的某个数字。找出这个缺失的数字。 示例 示例 1 输入: nums [3,0,1] 输出: 2示例 2 输入:…

Vivado - Aurora 8B/10B IP

目录 1. 简介 2. 设计调试 2.1 Physical Layer 2.2 Link Layer 2.3 Receiver 2.4 IP 接口 2.5 调试过程 2.5.1 Block Design 2.5.2 释放 gt_reset 2.5.3 观察数据 3. 实用技巧 3.1 GT 坐标与布局 3.1.1 选择器件并进行RTL分析 3.1.2 进入平面设计 3.1.3 收发器布…

git提交信息写错处理方式

在Git中&#xff0c;你可以通过使用rebase命令来合并提交记录。以下是一个简单的步骤来合并一系列提交&#xff1a; 使用git rebase -i开始交互式变基。在打开的编辑器中&#xff0c;你会看到一个提交列表。若要合并提交&#xff0c;将要合并的提交前面的pick改为squash或s。保…

【计算机网络 - 基础问题】每日 3 题(四十二)

✍个人博客&#xff1a;https://blog.csdn.net/Newin2020?typeblog &#x1f4e3;专栏地址&#xff1a;http://t.csdnimg.cn/fYaBd &#x1f4da;专栏简介&#xff1a;在这个专栏中&#xff0c;我将会分享 C 面试中常见的面试题给大家~ ❤️如果有收获的话&#xff0c;欢迎点赞…

ESP32 S3 语音识别 语音唤醒程序流程

ESP32 S3 语音识别 语音唤醒程序流程 参考例程首先进行esp_periph_set_init 初始化之后执行setup_player&#xff0c;之后执行start_recorder&#xff0c;识别的主处理voice_read_task 参考例程 D:\Espressif\esp-adf\examples\speech_recognition\wwe\ 首先进行esp_periph_se…