欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > uniapp vuex的使用

uniapp vuex的使用

2025/2/19 9:54:13 来源:https://blog.csdn.net/qq_19688207/article/details/143716985  浏览:    关键词:uniapp vuex的使用

实现组件全局(数据)管理的一种机制,可以方便的实现组件之间共享数据,不同于上述三种传递值的方式。

可以把vuex当成一个store仓库,可以集中管理共享的数据,并且存储在vuex中的数据都是响应式的,数据与页面同步。

一般情况下,只有组件之间共享的数据,才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data中。

注意:如果你使用的是HBuilderX,它已经内置了Vuex。如果你是使用npm或者yarn,可以通过以下命令安装:

安装vuex:
npm install vuex --save

1、创建Vuex的store:

在项目的src目录下创建一个store文件夹,然后在该文件夹中创建一个index.js文件,用于定义和配置Vuex store。

/* // 方式一import { createStore } from 'vuex';export default createStore({state() {return {count:0,// 定义一个名为 name 的状态//公共的变量,存储数据,这里的变量不能随便修改,只能通过触发mutations的方法才能改变};},mutations: {increment(state) {// 定义一个名为 increment 的修改状态方法state.count++;}//相当于同步的操作},actions: {increment({ commit }) {commit('increment');}//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变},getters: {count: (state) => state.count},}); */
// 方式二 推荐
import Vuex from 'vuex';
import {LoginPostMethod} from '@/api/api.js';const store = new Vuex.Store({state: {count:0,// 定义一个名为 name 的状态resToken: '',// 定义token//公共的变量,存储数据,这里的变量不能随便修改,只能通过触发mutations的方法才能改变},mutations: {increment(state) { // 定义一个名为 increment 的修改状态方法state.count ++;},setToken(state,token){// 定义一个名为 setToken 的修改状态方法console.log("state",state);console.log("token",token);state.resToken = token.resToken;uni.setStorageSync('resToken', token.resToken);},setEmptyToken(state){// 定义一个名为 setEmptyToken 的修改状态方法console.log("emptyState",state);state.resToken = '';uni.setStorageSync('resToken', null);},//相当于同步的操作},actions: {// 网络请求async logIn(context,apyload){console.log("context",context);console.log("apyload",apyload);const res = await LoginPostMethod(apyload)console.log('执行成功',res)if(res.success){const token = {resToken: res.token,}// 设置tokencontext.commit('setToken', token)}// 返回值return res;},//相当于异步的操作,不能直接改变state的值,只能通过触发mutations的方法才能改变}})export default store

 

2、在main.js中引入store并使用:

3.使用

import store from '@/store/index.js';//需要引入store***
export default{data(){return{}},methods:{addCountMethod() { // 定义一个名为 addMethod 的增加 count 的方法// 修改状态方法store.commit('increment');// 获取 state 中的 count 值const curcount = store.state.count;console.log("curcount",curcount);}, setMethodOne(){// 直接调用/store/index.js mutations中定义的方法store.commit("setEmptyToken");},setMethodTwo(){// 调用/store/index.js 中logIn方法const result = await store.dispatch('logIn', res)},}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com