Vuex在项目中的使用详解(1)

**

重中之重的一张图片

在这里插入图片描述
**

通常情况下,在组件项目中使用this.$store.state.dispatch可以将组件传到action

在组件项目中使用this.$store.state.commit传到Mutations中

引入Vuex的方法

npm install vuex --save

随后在项目的./src目录下创建一个名为store的文件夹,创建一个index.js文件完成如下设置

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)

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

图中将state,mutations分别作为组件引入,需分别完成store.js和mutations.js的创建

export default {
  changeCity (state, city) {
    state.city = city
    try {
      localStorage.city = city
    } catch (e) {}
  }
}
//一个mutatin.js示例
let defaultCity = '上海'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default {
  city: defaultCity
}
//一个state.js示例

完成以下设置后,不要忘记一个main.js的引入工作

import store from './store/index'

下面就可以快乐地使用vuex啦
如果是同步函数的操作即可略过dispatch操作,直接使用commit操作

	{{this.$store.state.city}}即可访问到Vuex中的state数据

在函数中声明如下代码

methods: {
    handleCityClick (city) {
       this.$store.commit('changeCity', city)
    },
  }

将city作为参数,提交到mutaion,执行changeCity函数,一个最简单的vuex即可被应用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值