vuex 回顾

安装和使用

//npm install vuex --save
//src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
   
	state:{
   
		count:0
	},
	mutations:{
   
		increment(state) {
   
			state.count++
		}
	}
})

export default store
//main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from './store'

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

正题

State 单一状态树

1、如何在Vue组件内获得Vuex的状态呢?

const Counter = {
   
  template: `<div>{
    { count }}</div>`,
  computed: {
   
    count () {
   
      return this.$store.state.count
    }
  }
}

每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。

2、mapState辅助函数摆脱每次将store里的状态声明为计算属性

当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。

//组件内使用
import {
    mapState } from 'vuex'
export defalut {
   
	//...
	computed: mapState({
   
		** 三种方式  'count' 等同于  state => state.count **
		count: state => state.count,
		countStr: 'count',
		countToUseThis(state) {
   
			return state.count + this.localCount
		}
	})
}

当映射的计算属性名称和state的子节点名称一致时,可以直接给mapState传一个字符串数组

computed: mapState([
	'count',
	'count1'
	...
])

3、mapState返回是一个对象,那组件自身使用的计算属性该怎么混搭使用呢?

mapState返回是一个对象,当我们组件内已经拥有了计算属性,该怎么办呢? 通常方法是将多个对象合并为一个,然后将最终值传个computed属性。 但是拥有 对象展开运算符 后, 使用就更为简单了。

computed:{
   
	localCompued() {
   },
	...mapState({
   
		** 三种方式  'count' 等同于  state => state.count **
		count: state => state.count,
		countStr: 'count',
		countToUseThis(state) {
   
		return state.count + this.localCount
	})
}

Getter

1、Getter是啥?

有时候我们需要从 store 中的 state 中派生出一些状态&

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值