vuex状态管理

103 阅读1分钟

vuex是vue的状态管理模式,采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

例如:大型项目中,有很多数据和操作,在多个组件中都需要用到,就可以使用vuex,对这些数据和操作进行集中管理。

1.在src目录下新建一个store文件夹,并在下面新建一个store.js文件,引入Vue和Vuex

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);//挂在vuex

//创建vuex对象
const store = new Vuex.Store({
	state: {
  	name: 'helloVuex'//存放的键值对就是所要管理的状态
  }
})

export default store

在main.js文件中引入store文件,并在Vue实例上挂载store

import Vue from 'vue'
import App from './app'
import router form './router'
import store from './store'

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

组件中使用vuex,例如在App.vue中 $store.state.name

<template>
    <div id='app'>
    name: 
    <h1>{{$store.state.name}}</h1>  //可以拿到store中的name属性:helloVuex
  </div>
</template>

//或在组件方法中使用
methods: {
    add() {
    console.log(this.$store.state.name)   //helloVuex
  }
}

vuex核心内容

state 存放状态

mutations state成员操作

getters 加工state成员给外界

actions 异步操作

modules 模块化状态管理