〖Vue〗小知识- Vuex-专为Vue准备的状态管理模式

133 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前文我们学习 Vue-Router路由的使用 , 本文就开始学习 Vuex 的相关内容了. 相对大一点的项目会比较复杂, 在各个页面间的数据传递就会比较麻烦, 这时候就会用到 Vuex全局状态管理工具了.

Vue Vuex 初识

Vuex 官方文档: vuex.vuejs.org/zh/

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

Vue 的组件间的 全局通信方案: Vuex

cnpm i vuex --save

建立一个仓库 在 src 中建立 store文件夹, 建立文件index.js

有需要在谷歌里面安装 vue开发者工具

import Vue from 'vue'
import Vuex from 'vuex' /// 引入

/// 注入
Vue.use(Vuex)

/// 注册一个 Vuex.Store
/// 内容 state对象即可存储需要用到的数据:比方说 这个n , 在组件内引入Vuex, 即可访问这个 state.num
var store = new Vuex.Store({
  state: {
    num: 100,
  },
})

Vuex 使用步骤:

Vuex(vuex store 唯一的)

image

  1. 建立文件夹 testvuex
  2. vue init webpack
  3. cnpm i vuex --save
  4. 建立一个仓库 在 src 中建立 store 文件夹,建立 index.js
  5. 存数据 state (需要在谷歌里面安装 vue 开发者工具)

模块化单独分离出来 -- store

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    student_id: 10001,
  },
})
console.log(store.state) // { student_id: 10001 }
export default store
  1. 然后 main.js 输入
 import store from './store',
  // 然后注册
//src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store, // 这里将 store 挂载到 Vue 实例上去
  components: { App },
  template: '<App/>',
})
  1. 读取数据: this.$store.state.变量
<template>
  <div id="app">{{ student_id }}</div>
</template>

<script>
  import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
  export default {
    name: 'App',
    data() {
      return {
        student_id: this.$store.state.student_id
      }
    }
    }
  }
</script>

参考 官方文档