关于vuex状态管理store的写法和应用(自学笔记)

 

具体安装使用

1 下载

npm install vuex -s

2 下载完成之后在src中创建一个 store 文件夹 创建一个store js文件

// store.js
import Vue from 'vue'
import Vuex from 'vuex'

// 让vue使用vuex工具来实现组件之间的数据共享
Vue.use(Vuex)

const state = {}
const mutations = {}
const actions = {}
const getters = {}
export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations
})

3 在main.js中 引入store.js 然后注入 store

// 引入store.js
import store from '@/store/store.js'

Vue.use(ElementUI)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    // 注入store
    store,
    components: { App },
    template: '<App/>'
})

4 定义

/ 存储数据的对象,我们可以将你需要存储的数据在这个state中定义
const state = {
  // 当前登陆的用户名
  username: ''
}
const mutations = {
  // 提供一个方法,为state中的username赋值
//   这些方法有一个默认的参数,这个参数就是当前store中的State
  setUserName (state, username) {
    //存入一个值
    state.username = username
    localStorage.setItem('myname', username)
  },
  getUserName (state) {
    //输出一个值
    return state.username
  }
}

//使用的时候---> 通过commit调用mutations中定义的函数,这个函数就是操作state中定义的成员的函数
   // this.$store.commit('setUserName', res.data.username(请求返回的值))


const actions = {
  setUserNameAction: ({commit}, username) => {
    commit('setUserName', username)
  },
  getUserNameAction: ({commit}) => {
    commit('getUserName')
  }
}

// 通过action来触发mutations中的函数,这种触发方式是异步方式--->使用
//存入  this.$store.dispatch('setUserNameAction', res.data.username + 'aa')
//取出  this.currentUserName = this.$store.dispatch('getUserNameAction')


//Getters是从 store 中的 state 中派生出一些状态,即当出现多处需要导入某个状态时,结果不是很理想,所以getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
const getters = {
  getUserName: (state) => {
    return localStorage.getItem('myname')
  }
}

//使用的时候   直接使用
// <span class="welcome">你好:{{$store.getters.getUserName}}</span>

5.原博客地址 Vuex的基本原理与使用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值