美文网首页
VUEX--随记

VUEX--随记

作者: 皇甫贝 | 来源:发表于2019-06-18 19:04 被阅读0次

1.VUEX--是啥
官网说明:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
个人理解:就是全局状态管理;多用于多组件之间的状态共享以及数据共享
2.VUEX--为啥用
统一管理防止分布管理引起的数据错误,如数据不一致

主要可以分为state getter mutation action module 五大块,个人的理解是 state (初始化数据)、getter (输出给外界数据) 、mutation (定义的方法)、action (输出给外界方法)、module(每一个js 文件都可以包含state getter mutation action四项,统一进行管理)

3.VUEX--咋用
1.VUEX引入
安装:npm install vuex --save
新建store文件夹,以及store.js
引入vuex,和申明使用vuex

 impor tVue from 'vue';
 import Vuex from 'vuex';
 Vue.use(Vuex);

创建仓库对象

const store = new Vuex.Store()
export default store

在main.js 文件中引入

  import store from '@/store/store';
  new Vue({
     el:"App",
     store,
  })

state:访问state对象,3种方法
方法1:使用this.$store

computed:{
  count(){
    return this.$store.state.count;
  }
}

方法2:使用mapState,注意: import时加{}

 import {mapState} from'vuex';
 computed:mapState({
    count:state=>state.count
 })

方法3:使用:mapState数组方法

computed:mapState(["count"])

2、mutations:同步修改数据
1)定义:

const mutations={
  add(state,n){
     state.count+=n;
  }
}

2)使用commit来调用mutations中的方法

@click="$store.commit('add',10)"

3)引用mapMutations,在methods中简化

methods:mapMutations([
      'add','reduce'
])

调用时,@click="reduce"

3、actions:异步修改数据
1)定义actions

const actions ={
   addAction(context){
      context.commit('add',10)
   },
   reduceAction({commit}){
      commit('reduce')
   }
}

2)调用方法同mutations

methods{
  ...mapMutations([
      'add','reduce'
   ]),
  ...mapActions([
    'addAction','reduceAction'
  ])
}

注意:使用... ES6语法
4、getters:数据过滤
1)定义

const getters = {
  count:function(state){
    returnstate.count +=100;
  }
}

2)使用

computed:{
  ...mapState(["count"]),
  count(){
    return this.$store.getters.count;
  }
}
//或者
...mapGetters(["count"])

5、模块化
1)定义模块

const moduleA={
   state,
   mutations,
   getters,
   actions
}

2)初始化store

export default new Vuex.Store({
  modules:{
      a:moduleA
  }
})

3)使用模块<h3>{{$store.state.a.count}}</h3>

computed:{
  count(){
     return this.$store.state.a.count;
  }
}

相关文章

  • VUEX--随记

    1.VUEX--是啥官网说明:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。个人理解:就是全局状...

  • vuex--基本使用

    vuex的作用 vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,解决vue中各个...

  • Vuex--严格模式

    开启严格模式 const store = new Vuex.Store({ // ... strict:true ...

  • Vuex——状态管理

    前言:项目中有使用Vuex,通过官网进行学习,现进行总结。 Vuex--状态管理模式 状态管理模式包含以下几个部分...

  • 2022-09-25

    随记

  • 测试,随记

    测试,随记

  • 海上

    邮轮随记

  • 随想

    随想随记

  • vuex--状态管理用法解析

    基本使用 state属性引用 state下的状态,可以在每个vue实例下通过this.$store.state.c...

  • 操作系统性能分析

    读书随随记

网友评论

      本文标题:VUEX--随记

      本文链接:https://www.haomeiwen.com/subject/nbdqqctx.html