Js开发-Vue技术-状态管理Plugin-Vuex

功能概念

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

Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

缺点: 如果您不打算开发大型单页应用 使用Vuex可能是繁琐冗余的。

 

vuex官方网站: https://vuex.vuejs.org/zh/ 

安装:npm install vuex --save 

① 数据流

1. 初始化store下index.js中的内容

import Vue from 'vue'
import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)
//创建VueX对象
const store = new Vuex.Store({
    state:{
        //存放的键值对就是所要管理的状态
        name:'helloVueX'
    }
})
export default store

2. 将store挂载到当前项目的Vue实例当中去

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:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
  components: { App },
  template: '<App/>'
})

3. HelloWorld.vue

<template>
  <div class="hello">
     name:
      <h1>{{ $store.state.name }}</h1>
      <button type="button" @click="add()"> test </button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods :{ 
    add(){
      console.log(this.$store.state.name)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

4. 安装Vue开发工具VueDevtools

在Vue项目开发中,需要监控项目中得各种值,为了提高效率,Vue提供了一款浏览器扩展——VueDevtools。

 

 

 

② VueX中的核心内容

在VueX对象中,其实不止有state,还有用来操作state中数据的方法集,以及当我们需要对state中的数据需要加工的方法集等等成员。

成员列表:
state 存放状态
mutations state成员操作
getters 加工state成员给外界
actions 异步操作
modules 模块化状态管理

 

 需要向后端请求时或者说出现异步操作时,需要dispatch VueX中actions的方法,以保证数据的同步

 

1. mutations是操作state数据的方法的集合比如对该数据的修改、增加、删除等等。

增删state中的成员为了配合Vue的响应式数据,我们在Mutations的方法中,应当使用Vue提供的方法来进行操作。如果使用delete或者xx.xx = xx的形式去删或增,则Vue不能对数据进行实时响应。

 

2. 可以对state中的成员加工后传递给外界

Getters中的方法有两个默认参数

state 当前VueX对象中的状态对象
getters 当前getters对象,用于将getters下的其他getter拿来用

 

3. 由于直接在mutation方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行异步操作,最终提交mutation方法。

Actions中的方法有两个默认参数

context 上下文(相当于箭头函数中的this)对象
payload 挂载参数

 

小结:Vuex

当项目庞大,状态非常多时,可以采用模块化管理模式。

Vuex 允许我们将 store 分割成模块(module)。

每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。

 

posted on 2019-08-09 14:10  小魔一剑  阅读(81)  评论(0)    收藏  举报