【vue-08】vuex

vuex的作用

简单理解,就是将多个组件共享的变量统一放到一个地方去管理,比如用户登录时的数据token。

快速上手

安装:npm install vuex

首先,我们在src文件夹下创建一个文件夹:store,在文件夹中创建一个index.js文件,写入以下代码。

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    },
    decrement(state) {
      state.count--
    }
  }
})
export default store

其次,我们要让所有的Vue组件都能使用这个store。就需要在main.js中引入。引入方式与router一致。

import Vue from 'vue'
import App from './App.vue'
import router from "./router"
import store from "./store"
Vue.config.productionTip = false

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

最后,使用App.vue

<template>
  <div>
    <h2>{{$store.state.count}}</h2>
    <button @click="addCount">增加</button>
    <button @click="delCount">减少</button>
  </div>
</template>
<script>
export default {
  name: 'about',
  methods: {
    addCount() {
      this.$store.commit('increment')
    },
    delCount() {
      this.$store.commit('decrement')
    }
  }
}
</script>

image-20210220085815179

这就是vuex最简单的使用方式。

  1. 提取出公共的store对象,用于保存在多个组件中共享的状态

  2. 将store对象放到Vue实例中,这样可以保证所有的组件都能使用到数据

  3. 在其他组件中使用store中的数据即可。

通过this.$store.state.属性,即可访问状态

通过this.$store.commit(‘名称’)即可访问mutations中对应的方法。

state中的状态可以直接进行修改,但是我们不建议这么修改。我们建议通过mutations去进行操作。

核心概念

State

Vuex提出使用单一状态树(单一数据源)。就是将一堆公用的数据放到一起去管理。如果你的状态信息是存放到多个Store中的,那么之后的管理和维护就会非常麻烦。

State类似于vue中data,用于定义全局信息。不建议直接修改state中的数据。

Getters

有时候,我们需要从state中获取一些经过改变后的数据,可以使用getter。同时,state中的数据不建议直接获取,最好是通过getter。

state: {
    count: 0,
    studentList: [
      {id: 3, name: '张三', age: 23},
      {id: 4, name: '李四', age: 24},
      {id: 5, name: '王五', age: 25},
      {id: 6, name: '赵六', age: 26}
    ]
  },
  getters: {
    getStudentByAge(state) {
      return state.studentList.filter(e => e.age > 24)
    }
  },

在页面中,就可以通过this.$store.getters.xxx获取 。这里获取的时候不加括号。

Mutations

通过mutations可以对数据进行修改,也可以传入其他参数。

Mutations类似于vue中的methods

Mutations中的方法,第一个参数一定是state,如果需要传参,从第二个参数开始。

mutations: {
    increment(state, n) {
      state.count += n
    },
    decrement(state) {
      state.count--
    }
  }

在其他组件中,如果需要调用mutations,直接使用this.$store.commit(‘方法名’, 参数列表)

posted @ 2020-09-03 18:27  DJ同学  阅读(118)  评论(0编辑  收藏  举报