# Vuex

## 1. 创建一个 store

```
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
    num: state => state.num
  },
  mutations: { // mutation 必须同步执行
    addNum(state) {
      state.num ++
    },
    changeNum(state, data) {
      state.num = data
    }
  },
  actions: { // 触发mutations，可以执行异步操作
    addNum(store) {
      setTimeout(() => {
        store.commit('addNum')
      }, 1000)
    },
    changeNum(store, data) {
      store.commit('changeNum', data)
    }
  }
})
export default store
```

## 2.引入store

```
// main.js
import Vue from 'vue'
import App from './App'
import store from './store'

new Vue({
  el: '#app',
  store,
  template: '<App/>',
  components: { App }
})
```

## 3.页面使用

{% hint style="info" %}
读取状态
{% endhint %}

```
// 通过计算属性获取
computed: {
    num() {
        return this.$store.state.num
    }
}

// 或者通过 mapGetters 函数获取
// store/index.js
getters: {
  num: state => state.num
},
// 组件内
import { mapState } from 'vuex'

computed: {
  ...mapGetters([
    'num'
  ])
}
```

{% hint style="info" %}
修改状态
{% endhint %}

```
// 组件内
this.$store.commit('addNum')
// 或者
this.$store.dispatch('addNum')
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yicoding.gitbook.io/vue/zu-jian-tong-xun/vuex.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
