第四十二章 Vue中使用mutations修改Vuex仓库数据

Vuex获取、修改参数值及异步数据处理 Vuex是专门为vue应用程序开发的状态管理模式,将组件的共享状态抽取出来,以一个全局单例模式进行管理,组件树构成一个巨大的视图,不管组件在树的何种位置,任何组件都能获取到状态和触发行为。可以将其想象为一个“前端数据库”(数据仓库),让其在各个页面上实现数据的共享包括状态,并且可操作。(核心就是 解决组件间的通讯问题) 阅读详情

目录

一、mutations修改仓库数据

1.1. 概述

1.2. mutations修改数据基本步骤

1.3. 完整代码

1.3.1. main.js

1.3.2. App.vue

1.3.3. index.js

1.3.4. Son1.vue

1.3.5. Son2.vue

二、mutations传参语法

2.1. mutations传参基本步骤

2.2. 完整代码

2.2.1. index.js

2.2.2. Son1.vue

三、输入框和Store仓库数据双向绑定

 1.3.1. main.js

1.3.2. App.vue

1.3.3. index.js

1.3.4. Son1.vue

1.3.5. Son2.vue


一、mutations修改仓库数据

1.1. 概述

在Vue中,明确vuex同样遵循单向数据流,即组件中不能直接修改仓库的数据,我们可以通过 strict: true 可以开启严格模式,防止在组件中非法修改仓库数据。

this.$store.state.count++ (错误写法)

在Vue中,组件想要修改Vuex的数据,可以通过Vue提供的mutations来实现。本章节我们将通过掌握mutations的操作流程,来修改state数据。 (state数据的修改只能通过mutations )

1.2. mutations修改数据基本步骤

1. 定义 mutations 对象,对象中存放修改 state 的方法

2. 组件中提交调用 mutations

1.3. 完整代码

1.3.1. main.js

import Vue from 'vue'
import App from './App.vue'
import store from '@/store/index'
console.log(store.state.count)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store
}).$mount('#app')

1.3.2. App.vue

<template>
  <div id="app">
    <h1>根组件 - {{ title }} - {{ count }}</h1>
    <input type="text">
    <Son1></Son1>
    <hr>
    <Son2></Son2>
  </div>
</template>

<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
import { mapState } from 'vuex'

export default {
  name: 'app',
  created () {
    console.log(this.$store.state.count)
  },
  data () {
    return {

    }
  },
  computed: {
    ...mapState(['count', 'title'])
  },
  components: {
    Son1,
    Son2
  }
}
</script>

<style>

</style>

1.3.3. index.js

// 存放的是vuex相关的核心代码
import Vue from 'vue'
import Vuex from 'vuex'

// 配置插件给Vue使用
Vue.use(Vuex)

// 创建仓库(空仓库)
const store = new Vuex.Store({
  // 严格模式(有利于初学者,检测不规范的代码 => 上线的时候可以去掉)
  strict: true,
  // 1. 通过 state提供数据(所有组件可以共享)
  state: {
    title: '大标题',
    count: 100
  },
  // 2. 通过 mutations 可以提供修改数据的方法
  mutations: {
    // 所有mutation函数,第一个参数,都是 state
    addCount (state) {
      // 修改数据
      state.count += 1
    },
    addFive (state) {
      state.count += 5
    },
    changeTitle (state) {
      state.title = '小标题'
    }
  }
})

// 导出给main.js使用
export default store

1.3.4. Son1.vue

<template>
  <div class="box">
    <h2>{{ $store.state.title }}</h2>
    从vuex中获取的值:<label>{{ $store.state.count }}</label>
    <br>
    <button @click="handleAdd">值 + 1</button>
    <button @click="addFive">值 + 5</button>
    <button @click="changeTitle">改标题</button>
  </div>
</template>

<script>
export default {
  name: 'Son1Com',
  methods: {
    handleAdd () {
      // 错误代码(vue默认不会监测,监测需要成本)
      // this.$store.state.count++
      // console.log(this.$store.state.count)

      // 应该通过 mutation 核心概念,进行修改仓库数据
      // 需要提交调用mutation
      this.$store.commit('addCount')
    },
    addFive () {
      this.$store.commit('addFive')
    },
    changeTitle () {
      this.$store.commit('changeTitle')
    }
  }
}
</script>

<style lang="css" scoped>
.box {
    border: 3px solid #ccc;
    width: 400px;
    padding: 10px;
    margin: 20px;
}
h2 {
    margin-top: 10px;
}
</style>

1.3.5. Son2.vue

<template>
    <div class="box">
      <h2>Son2 子组件</h2>
      从vuex中获取的值:<label>{{ count }}</label>
      <br>
      <button>值 - 1</button>
    </div>
  </template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Son2Com',
  computed: {
    ...mapState(['count'])
  }
}
</script>

<style lang="css" scoped>
.box {
    border: 3px solid #ccc;
    width: 400px;
    padding: 10px;
    margin: 20px;
}
h2 {
    margin-top: 10px;
}
</style>

二、mutations传参语法

2.1. mutations传参基本步骤

提交mutation还可以传递参数  `this.$store.commit( 'xxx', 参数 )`

1. 提供 mutation 函数 (带参数 - 提交载荷 payload )

2. 页面中提交调用 mutation

注:提交参数只能一个,如果有多个参数,需要将该参数包装成一个对象传递

2.2. 完整代码

2.2.1. index.js

// 存放的是vuex相关的核心代码
import Vue from 'vue'
import Vuex from 'vuex'

// 配置插件给Vue使用
Vue.use(Vuex)

// 创建仓库(空仓库)
const store = new Vuex.Store({
  // 严格模式(有利于初学者,检测不规范的代码 => 上线的时候可以去掉)
  strict: true,
  // 1. 通过 state提供数据(所有组件可以共享)
  state: {
    title: '大标题',
    count: 100
  },
  // 2. 通过 mutations 可以提供修改数据的方法
  mutations: {
    // 所有mutation函数,第一个参数,都是 state
    addCount (state, n) {
      // 修改数据
      state.count += n
    },
    subCount (state, n) {
      // 修改数据
      state.count -= n
    },
    changeTitle (state, obj) {
      state.title = obj.newTitle
    }
  }
})

// 导出给main.js使用
export default store

2.2.2. Son1.vue

<template>
  <div class="box">
    <h2>{{ $store.state.title }}</h2>
    从vuex中获取的值:<label>{{ $store.state.count }}</label>
    <br>
    <button @click="handleAdd(1)">值 + 1</button>
    <button @click="handleAdd(5)">值 + 5</button>
    <button @click="handleAdd(10)">值 + 10</button>
    <button @click="handleSub(1)">值 - 1</button>
    <button @click="handleSub(5)">值 - 5</button>
    <button @click="handleSub(10)">值 - 10</button>
    <button @click="changeTitle">改标题</button>
  </div>
</template>

<script>
export default {
  name: 'Son1Com',
  methods: {
    handleAdd (n) {
      // 错误代码(vue默认不会监测,监测需要成本)
      // this.$store.state.count++
      // console.log(this.$store.state.count)

      // 应该通过 mutation 核心概念,进行修改仓库数据
      // 需要提交调用mutation
      this.$store.commit('addCount', n)
    },
    handleSub (n) {
      this.$store.commit('subCount', n)
    },
    changeTitle () {
      this.$store.commit('changeTitle', { name: '王哲晓', newTitle: '2024加油,迎接新的开始,新的起点,新的人生' })
    }
  }
}
</script>

<style lang="css" scoped>
.box {
    border: 3px solid #ccc;
    width: 400px;
    padding: 10px;
    margin: 20px;
}
h2 {
    margin-top: 10px;
}
</style>

三、输入框和Store仓库数据双向绑定

 1.3.1. main.js

import Vue from 'vue'
import App from './App.vue'
import store from '@/store/index'
console.log(store.state.count)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store
}).$mount('#app')

1.3.2. App.vue

<template>
  <div id="app">
    <h1>根组件 - {{ title }} - {{ count }}</h1>
    <input :value="count" @input="handleInput" type="text">
    <Son1></Son1>
    <hr>
    <Son2></Son2>
  </div>
</template>

<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
import { mapState } from 'vuex'

export default {
  name: 'app',
  created () {
    console.log(this.$store.state.count)
  },
  data () {
    return {

    }
  },
  methods: {
    handleInput (e) {
      // 1.实时获取输入框的值
      const num = e.target.value
      // 2.提交mutation,调用mutation函数
      this.$store.commit('changeCount', num)
    }
  },
  computed: {
    ...mapState(['count', 'title'])
  },
  components: {
    Son1,
    Son2
  }
}
</script>

<style>

</style>

1.3.3. index.js

// 存放的是vuex相关的核心代码
import Vue from 'vue'
import Vuex from 'vuex'

// 配置插件给Vue使用
Vue.use(Vuex)

// 创建仓库(空仓库)
const store = new Vuex.Store({
  // 严格模式(有利于初学者,检测不规范的代码 => 上线的时候可以去掉)
  strict: true,
  // 1. 通过 state提供数据(所有组件可以共享)
  state: {
    title: '大标题',
    count: 100
  },
  // 2. 通过 mutations 可以提供修改数据的方法
  mutations: {
    // 所有mutation函数,第一个参数,都是 state
    addCount (state, n) {
      // 修改数据
      state.count += n
    },
    subCount (state, n) {
      // 修改数据
      state.count -= n
    },
    changeTitle (state, obj) {
      state.title = obj.newTitle
    },
    changeCount (state, newCount) {
      state.count = newCount
    }
  }
})

// 导出给main.js使用
export default store

1.3.4. Son1.vue

<template>
  <div class="box">
    <h2>{{ $store.state.title }}</h2>
    从vuex中获取的值:<label>{{ $store.state.count }}</label>
    <br>
    <button @click="handleAdd(1)">值 + 1</button>
    <button @click="handleAdd(5)">值 + 5</button>
    <button @click="handleAdd(10)">值 + 10</button>
    <button @click="handleSub(1)">值 - 1</button>
    <button @click="handleSub(5)">值 - 5</button>
    <button @click="handleSub(10)">值 - 10</button>
    <button @click="changeTitle">改标题</button>
  </div>
</template>

<script>
export default {
  name: 'Son1Com',
  methods: {
    handleAdd (n) {
      // 错误代码(vue默认不会监测,监测需要成本)
      // this.$store.state.count++
      // console.log(this.$store.state.count)

      // 应该通过 mutation 核心概念,进行修改仓库数据
      // 需要提交调用mutation
      this.$store.commit('addCount', n)
    },
    handleSub (n) {
      this.$store.commit('subCount', n)
    },
    changeTitle () {
      this.$store.commit('changeTitle', { name: '王哲晓', newTitle: '2024加油,迎接新的开始,新的起点,新的人生' })
    }
  }
}
</script>

<style lang="css" scoped>
.box {
    border: 3px solid #ccc;
    width: 400px;
    padding: 10px;
    margin: 20px;
}
h2 {
    margin-top: 10px;
}
</style>

1.3.5. Son2.vue

<template>
    <div class="box">
      <h2>Son2 子组件</h2>
      从vuex中获取的值:<label>{{ count }}</label>
      <br>
      <button>值 - 1</button>
    </div>
  </template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Son2Com',
  computed: {
    ...mapState(['count'])
  }
}
</script>

<style lang="css" scoped>
.box {
    border: 3px solid #ccc;
    width: 400px;
    padding: 10px;
    margin: 20px;
}
h2 {
    margin-top: 10px;
}
</style>

Vuex怎么使用,Vuex获取变量值,Vuex修改变量值和触发定义的方法! 今天来简单介绍一下Vuex在使用过程中应该怎么获取或者改变我们在state中声明的变量; 关于这个问题,其实答案有很多种,每个人的习惯都不太一样,而最为正确和最安全的方法我来大概介绍一下,希望可以帮到大家! 1.首先我们来引入vuex,里面的几个常用方法我就不一一介绍了,首先在state里面声明一个变量pathName,在定义一个方法savePath,第一个参数固定state,指向就是state本身,第二个参数是你调用方法时传的参数,如下图 // 在store里面的index.js文件写入 import 阅读详情

相关推荐

vue2(7)之vuex使用/state状态//mutations修改数据/getters/模块化module/获取模块内的数据state&getters与方法

目标:明确Vuex是什么,应用场景以及优势state: {count: 0},// 定义mutations})getters: {// getters函数的第一个参数是 state// 必须要有返回值,返回值就是getters的值// }

qq_66318904的博客 1759

Vuex中mutations的用法

Vuex中mutations的用法之一 在 Vuex 中 store 数据改变的唯一方法就是提交 mutations。mutations里面装着一些改变数据方法的集合,这是Vuex 设计很重要的一点,就是把处理数据逻辑方法全部放在 mutations 里面,使得数据和视图分离。 Mutations使用 Vuex 中的 mutations 非常类似于事件,每个 mutations 都有一个字符串的事件类型(type)和一个回调函数(handler),也可以理解为{type:handler()},这和订阅发布有

Anony_me的博客 1万+

Vuex -mutations 传参修改仓库数据

Vuex -mutations 传参修改仓库数据

Forever_Hopeful的博客 664

【Vue】mutations

mutations是vuex中的对象,这个对象可以定义在当前store的配置项中state: {count: 0},// 定义mutations// mutations是一个对象,对象中存放修改state的方法// 方法里参数 第一个参数是当前store的state属性// 第二个参数:payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷// 修改数据},})

qq_39921135的博客 1222

百度网盘开放平台OAuth 2.0授权全流程解析

本文详细解析了百度网盘开放平台OAuth 2.0授权全流程,包括创建应用、获取凭证、授权码模式详解以及access_token的使用与刷新。通过实际案例和代码示例,帮助开发者快速掌握接口调用技巧,避免常见错误,确保安全高效地接入百度网盘API。

wind6的博客 1282

Ferry工单平台部署

ferry工单平台部署

运维求生之路 1903

Vue中mutation介绍

定义:mutation是Vuex中改变store状态的唯一方法。Vuex的设计原则之一就是将处理数据逻辑的方法全部放在mutations中,以保持数据和视图的分离。作用:mutations提供了一种同步地更新状态的机制,确保每次状态变更都可以被追踪和记录。Vue中的mutation是Vuex状态管理库中的一个重要概念,它提供了一种同步地更改store状态的机制。通过mutations,我们可以确保每次状态变更都可以被追踪和记录,从而保持数据和视图的同步和一致性。

hexadecimal_001的博客 1275

vasp-自旋轨道耦合(SOC)计算步骤

在VASP中执行自旋轨道耦合(SOC)计算,具体的计算步骤如下: 结构优化获取CONTCAR文件 自洽计算(collinear normal VASP calculations)获取IBZKPT,CHGCAR和WAVECAR文件。 SCF+SOC计算,在此步骤中,将步骤2中的IBZKPT复制为KPOINTS,以便两个步骤具有相同的k网格,因此可以读取步骤2中的CHGCAR和WAVECAR文件。 能带结构计算,在此步骤中,将KPOINTS改为高对称点,读取步骤3中的CHGCAR和WAVECAR文件。

懒散的鱼与消失的猫 3万+

vue中使用vuex(超详细)

vuex是使用vue中必不可少的一部分,基于父子、兄弟组件,我们传值可能会很方便,但是如果是没有关联的组件之间要使用同一组数据,就显得很无能为力,那么vuex就很好的解决了我们这种问题,它相当于一个公共仓库,保存着所有组件都能共用的数据。 那么,我们一起来看看vue项目怎么使用它吧。(如果你对vuex有一定了解,不是刚接触的小白,请忽略第一步,直接查看第二步) 一、适合初学者使用,保存数据以及...

一只前端小菜鸟 18万+

十一、Cadence ic 617以及assura使用总结

1.617的端口和514不同,没有网络属性,使用时不能直接放在原理图上,如果要直接放在图上要接线并且放上标签。2.617的端口也不能直接放在线上,514中将端口直接放在线上是可以使端口和线连接,但617看似连接,但拉出来线没有交点,实际上没有连接。这里set switches里的选项表示不同的模块,也就是选择一个就只对这一部分进行DRC验证,要验证整个版图的DRC就要把所有的选项选中,然后一个个改正。LVS中也是一样,要全部选中改正。

0 2298

《八》:玩家位置同步(玩家防碰撞)

在VR大空间体验中,由于玩家佩戴头显设备无法直接观察彼此位置,容易发生碰撞。因此,需要将玩家的实时位置信息绘制在虚拟空间中,实现位置可视化。通过获取头显的位置和旋转角度等数据,可以推算出玩家的移动状态和位置。使用可序列化的玩家结构体,通过UDP将玩家数据发送到服务器,服务器接收并反序列化数据后,同步所有玩家的最新信息至各客户端。客户端根据接收到的数据渲染虚拟人物模型,实现动态位置更新。这一过程涉及数据序列化、反序列化、网络通信和实时渲染等技术,确保玩家在虚拟空间中的位置同步和可视化。

unitygroup的博客 420

【Vue】VueX仓库

vuex是一个vue的状态管理工具,状态就是数据大白话:vuex是一个插件,可以帮我们管理vue通用的数据(多组件共享的数据)

m0_62645012的博客 2064

YOLOv5_DeepSORT_Pytorch训练自己的多目标跟踪模型

1 准备 环境配置:https://blog.csdn.net/weixin_50008473/article/details/115250986?spm=1001.2014.3001.5501 YOLOv5_DeepSORT_Pytorch代码地址: https://github.com/mikel-brostrom/Yolov5_DeepSort_Pytorch DeepSORT论文:https://arxiv.org/pdf/1703.07402.pdf 2 训练目标检测模型 训练自己的目标检测模

weixin_50008473的博客 1万+

Vue—— vuex详解,彻底搞懂vuex

本文主要介绍vue中 Vuex 的相关知识点!!!!

Bonsoir777的博客 4万+

【华为OD机试真题 新系统】960、 面试叫号系统 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS)

【华为OD机试真题 2026C卷】960、 面试叫号系统 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS) 华为od机试,华为od机试真题,华为od机试E卷,华为odE卷,华为od机试真题E卷,华为OD,华为OD机试,华为OD机试真题,华为od机考,华为od机试D卷,华为od机试真题D卷,华为od手撕代码,华为od,华为od机试C卷,华为od e卷,华为2025e卷,od机试,2025E卷,华为OD机试E卷,什么是华为od,华为od介绍,全面了解华为od,2025华为od,如何备战华

KJ.JK 2376

K8S搭建(centos)四、安装K8S

每个人都有惰性,但不断学习是好好生活的根本,共勉!

感谢阅读 2663

Vue2-vuex使用

vuex是一个vue中的一个插件,可以帮我们管理vue通用(多组件共享)的数据state: {count: 0,},// 1.定义mutationsstate.count++//增加数据},state.count--//减少数据})

R20232844的博客 3561

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Vue2 - 09 Vuex的基本使用(state,mutations,actions,getters)

目标:明确Vuex是什么,应用场景以及优势state: {count: 0},// 定义mutations})通过mutations修改state的步骤1.定义 mutations 对象,对象中存放修改 state 的方法2.组件中提交调用 mutations(通过$store.commit('mutations的方法名'))getters: {// getters函数的第一个参数是 state// 必须要有返回值。

qq_56101688的博客 2234

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Vue2中vuex使用方法

在进行vue2项目开发的时候,我们有时会希望某些数据能够全局共享这时候vuex就能够帮到我们vuex可以将数据集中起来管理,我把vuex叫做一个仓库。在vue2中通常使用vuex3,在vue3中通常适合用vuex4,所以这里我们使用的是vuex3。

2302_77610294的博客 2569

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

vuex创建空仓库,store访问,mutations修改数据

构建多组件 数据共享环境vuex规定Vue版本是vue3,在此进行使用 npm install vuex --force 该命令忽略npm 忽略这种对等依赖的冲突情况,强制安装vuex。

m0_63178019的博客 555

vuex &store,mutations,getters,actions

目标:明确vuex是什么,应用场景,优势vuex是一个vue的状态管理工具,状态就是数据大白话:vuex是一个插件,可以帮我们管理vue通用的数据(多组件共享数据)①某个状态在很多个组件来使用(个人信息)②多个组件共同维护一份数据(购物车)①共同维护一份数据,数据集中化管理②响应式变化③操作简捷(vuex提供了一些辅助函数)

AYBBZXY的博客 1368

一文搞定Vuex仓库与数据访问

3actions:用于进行异步操作,相当于对mutations做一个包装,完成其不能完成的异步操作,注意,actions里的第一个参数为context上下文,当使用actions调用mutations的方法时要用context.commit(‘mutations方法名’,操作参数(可选))4.actions:这部分用于异步操作数据,如axios访问或者计时器处理为异步操作,一般在actions里会调用mutations里的方法,用来异步操作数据(mutations不能进行异步操作)与state很相似。

weixin_62952521的博客 1476

vuex 简单的 state与mutations 操作(创建仓库、修改仓库、读取仓库、计算属性)

打开控制台进入项目所在路径输入以下命令: npm install vuex --save cnpm install es6-promise --save import 'es6-promise/auto'//(注意:此引入在引用vuex之前添加) import Vuex from 'vuex' Vue.use(Vuex)

程序员小哲的博客 2555

Vue使用Vuex一步步封装并使用store

文章目录一、安装Vuex依赖二、一步步封装store1. main.js中全局引入store仓库(下一步创建)2. this.$store3. this.$store.state4. this.\$store.getters(this.\$store.state的升级)5. this.$store.commit('mutations')6. this.\$store.dispatch('actions')(this.\$store.commit('mutations')的升级)三、modules 模块化四、

GeniusXYT的博客 9959

vuex3的介绍与state、actions和mutations的使用

Vuex 是什么?Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

qq_56715703的博客 2676
上一篇: 第四十一章 Vue之初识VueX
下一篇: 第四十三章 Vue之mapMutations简化mutations操作
王哲晓
博客等级 码龄11年 1478粉丝 267原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值