vuex核心概念和基本使用

vuex

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

开始

安装
①直接下载方式
创建一个 vuex.js 文件 将https://unpkg.com/vuex这个网址里的内容放到该文件夹里。
②CND方式

<script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.js"></script>

③NPM方式

npm install vuex --save

④Yarn方式

yarn add vuex

NPM方式安装的使用方式
1.在 scr 文件里创建一个 store / index.js 的文件夹,写入以下内容。

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {}
})

2.在main.js 里引入,然后挂载到 Vue 实例里

import Vue from 'vue'
import store from './store'

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

store概念及使用

概念:

就是存储组件之间共享的数据。

只有 mutations 才能修改 store 中的数据

使用:

先定义后使用

定义
state: {
  num: 0
}
使用

方式1(推荐)

<div>{{ numAlias }}</div>



import { mapState } from 'vuex'

export default {
  //计算函数
  computed: mapState({
    // 传字符串参数 'count' 等同于 `state => state.count`
    numAlias: 'num',//常用key是自己起的名随便 value接收的数据
    
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
    
    //可以定义其余的计算函数
  }),
  
  //或者这样
  //计算函数
  computed: {
    mapState(['count'])
  }
}

方式2

<div>{{ $store.state.count }}</div>

mutations概念及使用

概念:

修改store里的数据,严格规定不能在其余的地方修改store的数据,mutations里不要执行异步操作。

mutation 必须同步执行,不能异步执行。

使用:

先定义方法后使用

定义
mutations: {
	//increment自定义方法 store参数是store数据, parameter参数是接收到的数据,可不要
	
    increment (state, parameter) {
        // 变更状态
        state.num++
    }
}
使用

方式1(推荐使用)

import { mapState, mapMutations } from 'vuex'

//方法
methods: {
	...mapMutations([
	    // mutations自定义的方法名
    	'increment'
    ]),
    love() {
    	// 直接this调用 this.increment('需要传过去的数据,可不要')
        this.increment('Bin')
    }
}

方式2

methods: {
    love() {
    	// this.$store.commit('自定义的名称', '传过去的数据,可不传')
    	this.$store.commit('increment', 'data')
    }
}

action概念及使用

概念:

用于处理异步操作。

如果通过异步操作变更数据,必须通过action,而不能使用mutation,但是在action中还是要通过触发mutation的方式间接变更数据。

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更数据(状态)。
  • Action 可以包含任意异步操作。
使用:
定义
mutations: {
	//increment自定义方法 store参数是store数据, parameter参数是接收到的数据,可不要
	
    increment (state, parameter) {
        // 变更状态
        state.num++
    }
},
actions: {
	//add 自定义方法 context是参数,可以把它当作vuex的实例
    add(context) {
    	//可以通过context.commit('mutations中需要调用的方法')
    	context.commit('increment')
    }
}
使用

方式1(推荐)

import { mapState, mapMutations, mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions([
      'add', // 将 `this.add()` 映射为 `this.$store.dispatch('add')`

      // `mapActions` 也支持载荷:
      'add' // 将 `this.add(amount)` 映射为 `this.$store.dispatch('add', amount)`
    ]),
    
    love() {
    	// 直接this调用 this.add('需要传过去的数据,可不要')
    	this.add(data)
    }
  }
}

方式2

methods: {
    love() {
    	// this.$store.dispatch('自定义的名称', '传过去的数据,可不传')
    	this.$store.dispatch('add', data)
    }
}

getters概念及使用

概念:

getter用于对store中的数据进行加工处理形成新的数据。getting可以对store中已有的数据加工处理之后形成新的数据,类似Vue的计算缩写。

使用:
定义
state: {
  num: 0
},
getters: {
    doneTodos: state => {
    	return state.num = 10
    }
}
使用

方式1(推荐)

<div>{{ doneTodos }}</div>



import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'

export default {
  //计算函数
  computed: {
  	...mapState(['count']),
  	...mapmapGetters(['doneTodos'])
  }
}

方式2

<div>{{ $store.getters.doneTodos }}</div>

modules的概念及使用

将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter

文件格式

├── index.html
├── main.js
└── store
    ├── index.js       
    └── modules
        ├── test.js   # test模块
        └── ......
定义

store / index.js 文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import test from "./modules/test"

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

test.js 文件

// state
const state = () => ({
  count: 0
})

// getters
const getters = {}

// actions
const actions = {
  asyncAdd(context) {
    setTimeout(() => {
      context.commit('adds')
    }, 1000)
  }
}

// mutations
const mutations = {
  adds(state) {
    state.count++
  }
}

export default {
  namespaced: true,  // 成为带命名空间的模块
  state,
  getters,
  actions,
  mutations
}
使用
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'


export default {
  computed: {
  	...mapState({
  		count: (state) => state.test.count
  	}),
  	...mapmapGetters({
  		doneTodos: (state) => state.test.doneTodos
  	})
  },
  methods: {
    ...mapMutations('test', ['add']),

    ...mapActions('test', ['asyncAdd']),
   }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值