vuex使用及方法介绍

vux核心--state声明变量

  1. src下新建文件夹  src/store/index.js

 



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

Vue.use(Vuex)   //挂载到vue上

const store = new Vuex.store({
    state:{
        属性名:值
    }
})

//导出store实例
export default store

2.在main.js 中引入

// 在入口文件中引入store
import store from './store/index.js'

// 挂载到vue的实例上
new Vue({
  store: store,
  render: h => h(App),
}).$mount('#app')

state变量使用

常规方法:

  • 模板中:{{ $store.state.属性名 }}

  • 配置项中:{{ this.$store.state.属性名 }}

mapState映射使用

  • 1.按需导入mapState函数
//从vuex中导入方法

import { mapState } from 'vuex'

 

  • 2.将函数映射到computed属性中
//传统方法
computed:{ 
    ...mapState(['state中的属性名']) 
}


//在组件中修改vuex中固定变量名使用
computed:{ 
    ...mapState({
        自定义属性名:state=>state.vuex中属性名
    }) 
}

总结

  • state中定义的数据都是响应式的,只要数据发生变化,任何一个使用到当前数据的组件都会得到更新

  • 如果我们想修改state中的某个数据,我们可以通过提交mutations的方式进行修改

vuex核心概念--mutations同步修改

  • 1.定义mutations
const store = new Vuex.store({
    state:{},
    mutations:{
        //第一个参数为当前state对象
        //第二个参数为外部调用时传参值
        函数名(state,参数2){
            //在此修改state中数据
        }
    }
})


//只有mutations中方法可以修改state中的数据
//也可以只有一个参数state
  • mutations定义完成之后,就等待被调用。它的作用是用来修改vuex中的数据

使用方法

  • 1.通过$store  提交mutations 
this.$store.commit('mutations中的函数名',传入的实参)
  • 2.通过mapMutations函数映射
//1.引入mapMutations函数
import {mapMutations} from 'vuex'

//2.在methods中展开使用
methods:{
    ...mapMutations(['mutations中函数名','函数名'])
}

核心概念

  • state

    • 获取

      • 直接使用。 this.$store.state.XXX

      • 映射使用。映射成组件内部的计算属性. computed: { ...mapState(['XXXX'])}

    • 设置

      • this.$store.state.XXX = 新值。(不推荐....)

      • mutations修改数据

  • 在vuex模式中,mutations是改变state的唯一的方式

vuex核心概念-actions异步修改

  • 1.定义actions
const store = new Vuex.Store({
    // ...其他代码(state:{},mutations:{})
    actions: {
        // context类似于$store对象
        // payload是传过来的参数值
        // 必须在actions里提交mutations来触发state更新(规定)
        asyncSubNum(context, payload){
            // 可以加入异步任务后, -> 触发mutations -> 修改state
            setTimeout(() => {
                context.commit("subNumFn", payload);
            }, 1000);
        }
    }
})

 

使用方法

  • 1.通过 $store使用action
this.$store.dispatch('action名称',payload)
  • 2.通过映射的方式分发actions
//从vuex中引入mapActions函数 
import {mapActions} from 'vuex'

//将vuex中的actions方法映射为methods中的方法 
 methods: {
            ...mapActions(["action名称"])
        }

vuex核心概念-getters计算属性

Getter 本质上是一个 JavaScript 函数,是 Vuex 中的“计算属性”:

Getter 可以依赖于 Store 中原始数据的变化,并返回计算后的新数据

Getter 的返回值会被缓存起来,只有依赖项发生变化时,Getter 的值才会被重新计算

  • 1.定义getters在store/index.js中
//举例


getters: { // vuex中的计算属性, 当state改变, 重新计算并缓存
    allCount(state){
        // 过滤选中的统计数量
        return state.goodsList.filter(obj => obj.goods_state).reduce((sum, obj) => sum += obj.goods_count, 0)
    },
        allPrice(state){
            return state.goodsList.filter(obj => obj.goods_state).reduce((sum, obj) => sum += obj.goods_count * obj.goods_price, 0)
        }
}

组件中使用getters

  • 1.通过$store使用getters

 

{{ $store.getters.allPrice }}
  • 2.通过映射的方式分发getters
// 通过vuex引入mapGetters方法(专门负责把vuex里数据导出到这里的)
import {mapGetters} from 'vuex'
export default {
    // ...省略了其他代码
    computed: {
        ...mapGetters(['allCount']) // 映射到computed身上一个allCount属性和vuex里关联的值
    },
};

命名空间

  • 防止多个modules之间, 如果定义的state/mutations/actions/getters里属性重名

  • 配置

const 模块名 = {
    namespaced: true, //开启命名空间
    //影响所有辅助函数(除了mapState)的使用
    
    state(){
        return 值
    }.
    mutations:{
    
}
    
}
  • 使用
...mapxxxx("命名空间", ['函数名'])

...mapxxxx("命名空间/函数名"])

methods: {
    ...mapActions("命名空间", ['定义的函数名'])
},

模块

  • 定义模块
//自定义模块
const moduleUser = {
    // 每个module都是独立的, 所以这里是用函数返回对象方式
    state (){
        return {
            username: "播仔",
            nickname: "可爱的猴子"
        }
    },
    mutations: {
        
    },
    actions: {
       
    },
    getters: {
       
    }
}

export default moduleUser
  • 注册模块
import Vue from 'vue'
import Vuex from 'vuex'
import moduleShopCar from './modules/模块名'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        模块名
    }
})

export default store
  • 使用
goodList为模块中state的值
//方法一
$store.state.模块名.goodsList

//方法二
...mapState({
    // 带命名空间以后
    goodsList: state => state.模块名.goodsList
})

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Uniapp 使用 Vuex,可以实现全局状态管理。下面是一个简单的示例,介绍如何在 Uniapp 使用 Vuex。 1. 首先,在你的项目安装 Vuex: ```bash npm install vuex ``` 2. 在你的项目创建一个 `store` 目录,用于存放 Vuex 相关的文件。 3. 在 `store` 目录下创建一个 `index.js` 文件,用于配置 Vuex 的核心内容。 ```javascript // store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ }, decrement(state) { state.count-- } }, actions: { increment(context) { context.commit('increment') }, decrement(context) { context.commit('decrement') } }, getters: { getCount(state) { return state.count } } }) export default store ``` 在上述代码,我们定义了一个包含 `state`、`mutations`、`actions` 和 `getters` 的 Vuex store。`state` 用于存储应用的状态,`mutations` 用于修改状态,`actions` 用于提交 mutations,`getters` 用于获取状态。 4. 在主入口文件 `main.js` 导入并挂载 Vuex store: ```javascript // main.js import Vue from 'vue' import App from './App' import store from './store' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ store, ...App }) app.$mount() ``` 在上述代码,我们将创建的 Vuex store 对象导入并挂载到 Vue 实例上,这样就可以在整个应用共享该 store 定义的状态和方法。 5. 现在,你可以在组件使用 Vuex 了。例如,在一个组件获取和修改状态: ```vue <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="decrement">Decrement</button> </div> </template> <script> export default { computed: { count() { return this.$store.getters.getCount } }, methods: { increment() { this.$store.dispatch('increment') }, decrement() { this.$store.dispatch('decrement') } } } </script> ``` 在上述代码,我们通过 `$store` 访问 Vuex store 对象,使用 `getters` 获取状态,使用 `dispatch` 提交 actions。 这样,你就可以在 Uniapp 使用 Vuex 进行全局状态管理了。希望对你有所帮助!如果有任何疑问,请随时提出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值