VueX的store的简单使用心结

vuex的特点:

多组件共享状态: 多个组件使用同一个数据
任何一个组件发生改变, 其他组件也要跟着发生相应的变化

安装vuex npm install vuex:

创建实例:
在这里插入图片描述

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

const state = {
  name : '张三',
  age  : 18
}
const mutations = {
  // 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
  changeName (state, params) {
  	state.name = params.name
  },
  changeAge (state, params) {
  	state.age = params.age
  }
}
const actions = {
	// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation
  actionsChangeAge ( context, params) {
  	context.commit('changeAge', params)
  }
}
const getters = {
  // Getter 接受 state 作为其第一个参数
  doubleAge (state) {
  	return state.age * 2
  }
  // 也可以使用箭头函数的简写
  // doubleAge: state => state.age * 2
}

const store = new Vuex.Store({ // 创建全局状态管理的实例
  state, // 共同维护的全局状态
  mutations, // 处理数据的唯一途径, 修改state的数据只能通过mutations
  actions, // 数据的异步操作处理
  getters // 获取数据并渲染
})

// 导出并在main.js里面引用&注册
export default store


# 引入文件:
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
Vue.config.productionTip = false

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


# 模板:

<template>
  <div>
    <h2>组件</h2>
    <!-- 组件可以通过this.$store.state 获取store中的数据 -->
    name: {{ this.$store.state.name }} <br>
    age: {{ this.$store.state.age }}
    <button @click="change">修改年龄</button>
  </div>
</template>
<script>
export default {
  methods: {
    change () {
      // 此方法一般用于网络请求
      // dispatch: 调用actions里面的方法, 再让actions里面的方法
      // 通过commit 调用mutations里面的方法
      this.$store.dispatch('actionsChangeAge', { age: 120 })
    },
    changeName () {
        // 通过$store.commit直接调用store实例中mutation里面的方法
        // 参数1: 要调用mutation里面的方法名, 参数2: 要传输的数据
        this.$store.commit('changeName', { name: '宝宝', age: 19})
    }
  }
}
</script>
----------------------------------------------------------------


// 以载荷形式
store.commit('increment'{
  amount: 10   //这是额外的参数
})


// 或者使用对象风格的提交方式
store.commit({
  type: 'increment',
  amount: 10   //这是额外的参数
})

dispatch:含有异步操作,数据提交至 actions ,可用于向后台提交数据
this.$store.dispatch('isLogin', true);

commit:同步操作,数据提交至 mutations ,可用于读取用户信息写到缓存里
this.$store.commit('loginStatus', 1);



state	存放基本数据
getters	从state基本数据派生出的数据(类似vue中的computed)
mutations	Store中更改state数据状态的唯一途径
actions	通过dispatch触发actions, actions在通过commit触发mutations。一般用于处理异步操作
modules	模块化Vuex


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神の愛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值