目录
一、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) {
// 修改