vue3 在store的index.js

发布于:2024-10-15 ⋅ 阅读:(69) ⋅ 点赞:(0)

导入vuex,在store的index.js创建store对象

在main.js挂载store

import store from './store'

new Vue ({

/* 将store对象实例挂载到vue实例中
所有组件就可以直接从store中获取全局数据了*/
store,
render: h => h(App)
}).$mount('#app')

在store中的index.js进行声明state

/* 创建store对象并导出 */
export default new Vuex.Store({
  // 状态--数据
  state: {
    /* state 中存放的就是全局共享的数据 */
    count: 0
  }
})

使用state数据

方法1:直接获取$store.state.数据名称
  <div>
  <!-- 组件访问 State 中数据的第一种方式:
  this.$store.state.全局数据名称 -->
    <h3>当前最新的count值为:{{$store.state.count}}</h3>
    <button>+1</button>
  </div>

方法2:mapState辅助函数

  • 从 vuex 中按需导入 mapState 函数
  • 在计算属性节点computed下映射   ...mapState(['count'])

Mutation(修改state数据的唯一方法)

不可以直接操作 Store 中的数据,可以集中监控所有数据的变。

在组件内触发mutation

方法一 commit函数,可以传参
  • 无参:this.$store.commit('add', )
  • 有参:this.$store.commit('addN', 3)
第二种方式(mapMutations辅助函数,可以传参)
  • 先导入mapMutation函数,
  • 再在methods中使用 ...mapMutations(['sub', 'subN']),  
  • 在click绑定的事件直接调用sub和传参的sub(5)

Action(作用是操作mutations异步请求)

异步操作变更数据,必须通过 Action,不能使用 Mutation,但在 Action 中要通过触发 Mutation 的方式间接变更数据。


1.定义actions:


在action中,不能直接修改state中的数据,必须从context.commit()触发某个mutation才行

context是个对象

2.触发actions分发

方法一dispatch函数,可以传参

无参: this.$store.dispatch('addAsync')

有参:this.$store.dispatch('addNAsync', 5)

dispatch函数专门触发actions的方法。

方法二mapActions辅助函数,可以传参
先导入mapActions函数,
再在methods中使用 ...mapActions(['subASync', 'subNASync'])
在click绑定的事件直接调用subASync和传参的subNASync(9)

Getter (类似于计算属性,不改变state值只加工)

Getter 用于对 Store 中的数据进行加工处理形成新的数据。

① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性。

② Store 中数据发生变化,Getter 的数据也会跟着变化。

1.使用getters

方法一

直接使用this.$store.getters.名称 

方法二

mapGetters辅助函数

  • 从 vuex 中按需导入mapGetters函数
  • 在计算属性节点computed下映射 ...mapGetters(['showNum']

module(模块化)

把 Vuex 相关代码分割到模块中,将 store 分割成模块(module),每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块.


网站公告

今日签到

点亮在社区的每一天
去签到