学习笔记,如有错误与疏忽,欢迎大佬指出纠正
阅读这篇文章需要的前置知识——vuex中store有关概念
使用vuex的前置条件——创建sotre对象
1.npm安装包
//vuex默认安装的是4.x版本,只能在vue3中使用
npm i vuex
//在vue2中安装vuex
npm i vuex@3
2.components同级下创建 store 目录
在内部创建index.js文件,编写
// 从vuex中导入store的构造方法
import { createStore } from 'vuex'
//声明store的三个最基础的组成部分
const mutations = {}
const actions = {}
const state = {}
//创建一个新的store实例,然后挂载上面的三个对象
const store = createStore({
//key: value同名同值,可以简写
actions,
mutations,
state
})
//导出store实例
export default store
3.在main.js导入并安装我们刚写好的store,【4,6行】
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import store from './store'//当目录下的js文件名为index.js时,可以省略不写文件名
const app = createApp(App)
app.use(store)
app.mount('#app')
4.在任意组件中使用this.$store来访问 store对象
created(){
console.log(this.$store)
}
实现集中式管理数据——以访问和修改state中数据的值为例
1.要想组件修改store中的数据,需要在组件中通过 this.$store.dispatch 或者 this.$store.commit 来指定方法,传递数据,
(1.1) 当修改数据具有逻辑性或网络请求,先通过dispatch派遣数据到Actions中
注意第一个参数为actions中想要调用的方法名,第二个参数为该方法的参数
//在组件中
increOdd(){
this.$store.dispatch("addOdd",this.chooseNum)
},
(1.2) 在actions对象中书写处理方法,完成后调用commit执行mutations中的某一方法 【跳转到第(3)步】
注意actions对象中的方法有两个参数 function(context,val)
context /上下文 封装了acitons前后需要用到的某些方法,如可以通过 context.commit(val) 来进入mutations中
val 是用户在调用 dispatch(context,val) 时传递的第二个参数值
//在index.js中
const actions = {
addOdd(context,val){
//判断传递的值如果是奇数则增加val的值
if (val % 2 != 0){
context.commit(AddOdd,val)//调用mutations中的AddOdd方法
}
}
}
(2) 当数据不需要进行逻辑相关的处理时,在组件中直接调用commit方法,指定mutations要调用的方法和要传递给该方法的参数
//在组件中
incre(){
this.$store.commit("ADD",this.chooseNum)
},
(3) 在mutations中书写commit要调用的方法
注意mutations对象中的方法有两个参数 function(state,val)
state为存放数据的对象
val为commit传递的第二个参数
//在index.js中
const mutations = {
AddOdd(state,val) {
state.count += val
}
}
(4) 在组件中 使用 this.$store.state.name 来访问名为name数据
在组件中
<h3>value = {{$store.state.count}}</h3>