在vue项目中使用vuex

首先在npm中安装vuex

npm install vuex --save-dev

clipboard.png

安装成功

在vue项目目录下建立store文件夹

clipboard.png

需要在项目main.js文件中引入store

import store from './store/index'

省略代码.....

new Vue({
  el: '#app',
  router,
  store,
  data:{},
  components: { App },
  template: '<App/>'
})

接下来在store中,建立以下目录文件

clipboard.png

在store的index.js中

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

import logIn from './modules/logIn'

Vue.use(Vuex);

引入vue和vuex,还有状态文件logIn.js

const state = {}
const actions = {}
const mutations = {}
const store = new Vuex.Store({
  modules: {
    logIn
  },
  actions,
  state,
  mutations,
})
export default store;

在logIn.js中写入需要的状态

// initial state
const state = {
  session_id: "",
  user: "",
  userImage:""
}

const getters = {}

const actions = {}

const mutations = {
  getSession_id(state, value) {
    state.session_id = value;
  },
  getUser(state, value) {
    state.usermobile = value;
  },
  getUserImage(state, value) {
    state.userImage = value;
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

使用

在使用的时候,要修改logIn.js中session_id的值,可以这样改变

$this.$store.commit("logIn/getSession_id", res.data.session_id);

如果想获取session_id的值,可以这样

computed:{
      session_id(){
        return this.$store.state.logIn.session_id; 
    },
  }

到此,vuex就可以在项目中使用了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值