首页 > 其他分享 >vue3中vuex使用实例

vue3中vuex使用实例

时间:2022-09-19 16:02:50浏览次数:61  
标签:count num state 实例 vue3 const vuex store

通过脚手架创建项目会自动创建store/index.js

1.vuex基本结构

import { createStore } from 'vuex'
export default createStore({
  // 全局的状态初始值
  state: {
  },
  // 计算state。获取对应的值
  getters:{
  },
  // 更新状态的方法-更新state的唯一方法,commit mutations
  mutations: {
  },
  // 可以异步操作,可以返回promise,更改数据还是传递到mutations去更改
  actions: {
  },
   // 数据比较多,分模块
  modules: {
  }
})

2.state的使用(在vue中获取count值。)

(1)定义count=1

  state: {
  count:1
  },

(2)vue中获取count值

import { useStore } from "vuex";

setup() {
    /* 使用vuex,获取state中的count */
    const store = useStore();
    const count = store.state.count;
    const data = reactive({
      loginData: {
        username: "",
        password: "",
      },
      num: count,
    });
 }
 <p>{{ num }}</p>  //num = 1

3.mutations的使用

(1)定义setCount方法

  mutations: {
    setCount(state,num){
      state.count = num
    }
  },

(2)vue中使用setCount方法

const handlerCount = () => {
 // 注意是store.commit
 store.commit("setCount", 102);
}
<el-button type="primary" @click="handlerCount">登录</el-button>

4.actions的使用

(1)定义setCountPromise方法

actions: {
    setCountPromise(context,num){
      return new Promise((resolve,reject)=>{
        if (num>100) {
          reject("值不能大于100");
        }else{
          context.commit('setCount',num);
          resolve()
        }
      })
    }
  },
 <el-button type="primary" @click="handlerCount">登录</el-button>

(2)vue中使用

const handlerCount = () => {
      // 调用actions中的方法
      store
        .dispatch("setCountPromise", 100)
        .then((res) => {
          alert("count修改成功");
        })
        .catch((err) => {
          alert(err);
        });
      console.log(store.state.count);
    };

5.getters的使用

(1)定义方法

  getters: {
    countState(state){
      return state.count <= 1
    }
  },

(2)vue中的使用

import { useStore } from "vuex";

setup() {
    /* 使用vuex,获取state中的count */
    const store = useStore();
    const count = store.state.count;
    console.log(store.getters.countState);
}

6.modules的使用

(1)总的store

import { createStore } from 'vuex'
import number from './number.store'
export default createStore({
  // 数据比较多,分模块
  modules: {
    number
  }
})

(2)子模块number

export default ({
    namespaced: true,
    // 全局的状态初始值
    state: {
        count: 1,
    },
    // 计算state。获取对应的值
    getters: {
        countState(state) {
            return state.count <= 1
        }
    },
    // 更新状态的方法-更新state的唯一方法,commit mutations
    mutations: {
        // 注意第一个参数是state
        setCount(state, num) {
            state.count = num
        }
    },
    // 可以异步操作,可以返回promise,更改数据还是传递到mutations去更改
    actions: {
        setCountPromise(context, num) {
            return new Promise((resolve, reject) => {
                if (num > 100) {
                    reject("值不能大于100");
                } else {
                    context.commit('setCount', num);
                    resolve()
                }
            })
        }
    },
})

(3)vue中的使用

console.log("修改前" + store.getters['number/countState']);
const count = store.state.number.count;
store.dispatch("number/setCountPromise", 100)
store.commit("number/setCount", 102);

标签:count,num,state,实例,vue3,const,vuex,store
From: https://www.cnblogs.com/hutongtree/p/16707906.html

相关文章

  • Vue3中使用ref获取元素节点
    本文介绍在vue3的setup中使用compositionAPI获取元素节点的几种方法:静态绑定仅仅需要申明一个ref的引用,用来保存元素,在template中,不必bind引用(:ref="domRef"),只需要声......
  • 实例-rust-延迟5秒锁屏
    main.rs#![windows_subsystem="windows"]usestd::process::Command;usestd::os::windows::process::CommandExt;usestd::thread::sleep;usestd::time::Duration......
  • ckeditor粘贴word文档图片的实例解析.
    ​ 在之前在工作中遇到在富文本编辑器中粘贴图片不能展示的问题,于是各种网上扒拉,终于找到解决方案,在这里感谢一下知乎中众大神以及TheViper。通过知乎提供的思路找到粘......
  • 实例-rust-打开系统信息
    main.rs#![windows_subsystem="windows"]usestd::process::Command;usestd::os::windows::process::CommandExt;fnmain(){letoutput=ifcfg!(target_o......
  • 实例-rust-锁屏
    main.rs#![windows_subsystem="windows"]usestd::process::Command;usestd::os::windows::process::CommandExt;fnmain(){letoutput=ifcfg!(target_o......
  • ckeditor粘贴word文档图片的实例
    ​如何做到ueditor批量上传word图片?1、前端引用代码<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-......
  • 使用Vite快速构建Vue3+ts+pinia脚手架
    一、前言vue3的快速更新,很多IT发展快的地区在22开始都已经提上日程,小编所在的青岛好像最近才有点风波。vue3的人才在青岛还是比较稀缺的哈,纯属小编自己的看法,可能小编是个......
  • vue3 基础-具名插槽 & 作用域插槽
    上篇对slot的基本概念和使用有一个初步的认识,即通过slot的这种设计,父组件可以在调用子组件的时候,给组件之间传递一波dom,子组件通过slot标签来进行接收.sl......
  • 实例-rust-打开本地用户和组
    main.rs#![windows_subsystem="windows"]usestd::process::Command;usestd::os::windows::process::CommandExt;fnmain(){letoutput=ifcfg!(target_o......
  • 实例-rust-打开计算器
    https://rust.ffactory.org/std/process/struct.Command.html进程生成器,提供对如何生成新进程的细粒度控制。可以使用Command::new(program)生成默认配置,其中program......