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

目录

一、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) {
      // 修改
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值