Vuex 的环境搭建和基本使用

1. Vuex 是什么?

  1. 定义:专门在 vue 中实现 集中式状态(数据)管理的一个 vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

  2. github 地址: https://github.com/vuejs/vuex

2. 什么时候使用 vuex?

  1. 多个组件依赖于同一状态

  2. 来自不同组件的行为需要变更同一状态

3. Vuex 原理图

            谷歌浏览器的开发者工具 Devtools 是和 mutations 进行交互的,当 触发了 mutations,devtools 的值就会更新,

 

              state:状态就是数据,数据保管在state对象中,比如保管一个sum的属性

 

              actions: $store.dispatch('action 中的方法名',数据) :1 加减乘除2加减乘除几。actions也是一个对象,actions有和加减乘除对应的key对应的函数,当用dispatch调用时,就会调用actions中对应的加减乘除函数。

 

              mutations: 在actions中的 加减乘除中会 commit(‘add’, 2) ,提交给 mutations 这里。mutations 也是对象,里面有 add 对应的函数,函数中可以拿到 state对象和传过来的数据(几),然后对 state.sum += 2。

 

              注:actions 看起来好像挺多余,只是给Mutations去传话的,但是backend API是后端接口。当需要发ajax请求拿到下发的数据(加几)时,就要在actions中去调用异步函数。如果不用异步函数,就可以直接调用commit(),直接走到mutations。

 

              Vue components是客人,要点一份蛋炒饭(加二),actions是服务员,知道把菜单提交(commit)给后厨Mutations,后厨加工好,就上菜(改变state)。如果跟后厨很熟,就可以直接越过服务员,和后厨对话。

 

              如果奇数再加二,就要在actions中处理

 

              Store 管理 actions、mutations、state 这三个。(买一辆车得上牌子)

 

              store.dispatch()、store.commit()。 Vuex工作靠store。

 

 

 

 

 

4. 搭建 Vuex 环境

  首先,需要安装 vuex:

 

 npm i vuex
Vue.use(Vuex)
  • 文件目录结构:

  

 

  •  main.js 入口文件
// main.js 入口文件
import Vue from 'vue'
import App from './components/App.vue'
import store from './store/index'
var vm = new Vue({
    el: "#app",
    store,
    components: { App },
    render: c => c(App)
})
console.log(vm)
  •  store 目录下的 index.js
// 该文件用于创建 vuex 中最为核心的 store
import Vue from 'vue'
// 引入 vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备 actions —— 用于响应组件中的动作
const actions = {}
// 准备 mutations —— 用于操作数据(state)
const mutations = {}
// 准备 state —— 用于存储数据
const state = {}

export default new Vuex.Store({
    actions,
    mutations,
    state,
})
  • App.vue 文件

 

<template>
  <div>
      <h1>{{msg}}</h1>
      <Count/>
  </div>
</template>
<script>
import Count from './components/Count.vue'
export default {
  name: 'App',
  data() {
    return {
      msg: '今天天气真好啊'
    }
  },
  mounted() {
    console.log(this)
  },
  components: {
    Count,
  }
}
</script>

 

 

5. 求和案例 (基本使用)

  •  Count.vue
<template>
    <div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">当前求和为奇数再加</button>
        <button @click="incrementWait">等一等再加</button>
    </div>
</template>
<script>
export default {
    name: 'Count',
    data() {
        return {
            n:1, // 用户选择的数字
        }
    },
    methods: {
        increment() {
            this.$store.commit('ADD', this.n) // commit 直接和 mutations 对话,操作数据
        },
        decrement() {
            this.$store.commit('DECREMENT', this.n)
        },
        incrementOdd() {
            this.$store.dispatch('addOdd', this.n) // dispatch 和 actions 对话
        },
        incrementWait() {
            this.$store.dispatch('addWait', this.n)
        }
    },
    mounted() {
        console.log(this)
    }
}
</script>
  • store 目录下的 index.js
// 该文件用于创建 vuex 中最为核心的 store
import Vue from 'vue'
// 引入 vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备 actions —— 用于响应组件中的动作
const actions = {
    addOdd(context, value) {
        if (context.state.sum % 2) {
            context.commit('ADD', value)
        }
    },
    addWait(context, value) {
        setTimeout(() => {
            context.commit('ADD', value)
        }, 500)
    }
}
// 准备 mutations —— 用于操作数据(state)
const mutations = {
    ADD(state, value) {
        state.sum += value
    },
    DECREMENT(state, value) {
        state.sum -= value
    },
}
// 准备 state —— 用于存储数据
const state = {
    sum: 0, // 当前的和
}

export default new Vuex.Store({
    actions,
    mutations,
    state,
})
  • 组件中读取 vuex 中的数据: $store.state.sum
  • 组件中修改 vuex 中的数据:$store.dispatch('action 中的方法名',数据) $store.commit('mutations中的方法名',数据)

     备注:若没有网络请求或其他业务逻辑,组件中也可以越过 actions,即不写 dispatch,直接写 commit

 

6. getters 的使用

  6.1. 定义: 当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工。

  6.2. 在 store.js 中 追加 getters 配置

  • index.js
// 该文件用于创建 vuex 中最为核心的 store
import Vue from 'vue'
// 引入 vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备 actions —— 用于响应组件中的动作
const actions = {
    addOdd(context, value) {
        if (context.state.sum % 2) {
            context.commit('ADD', value)
        }
    },
    addWait(context, value) {
        setTimeout(() => {
            context.commit('ADD', value)
        }, 500)
    }
}
// 准备 mutations —— 用于操作数据(state)
const mutations = {
    ADD(state, value) {
        state.sum += value
    },
    DECREMENT(state, value) {
        state.sum -= value
    },
}
// 准备 state —— 用于存储数据
const state = {
    sum: 0, // 当前的和
}
// 准备 getters —— 用于将 state 中的数据进行加工
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}

export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters,
})

  6.3  组件中读取数据: $store.getters.bigSum

<template>
    <div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <h1>当前求和放大十倍为:{{$store.getters.bigSum}}</h1>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">当前求和为奇数再加</button>
        <button @click="incrementWait">等一等再加</button>
    </div>
</template>
<script>
export default {
    name: 'Count',
    data() {
        return {
            n:1, // 用户选择的数字
        }
    },
    methods: {
        increment() {
            this.$store.commit('ADD', this.n) // commit 直接和 mutations 对话,操作数据
        },
        decrement() {
            this.$store.commit('DECREMENT', this.n)
        },
        incrementOdd() {
            this.$store.dispatch('addOdd', this.n) // dispatch 和 actions 对话
        },
        incrementWait() {
            this.$store.dispatch('addWait', this.n)
        }
    },
    mounted() {
        console.log(this.$store)
    }
}
</script>

 

   6.4 state 与 getters 和 vue 中的 data 与  computed 十分相似,一个是数据源,一个对数据进行加工

 

 

 

 

posted @ 2021-12-12 11:25  我就尝一口  阅读(136)  评论(0编辑  收藏  举报