草庐IT

vuex中this.$store.commit和this.$store.dispatch的用法

老电影故事 2023-04-04 原文

前言

this. s t o r e . d i s p a t c h ( ) 与 t h i s . store.dispatch() 与 this. store.dispatch()this.store.commit()方法的区别总的来说他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state

区别

  • this.$store.commit()
    同步操作
this.$store.commit('方法名',)【存储】

this.$store.state.方法名【取值】
  • this.$store.dispatch()
    异步操作
this.$store.dispatch('方法名',)【存储】

this.$store.getters.方法名【取值】

当操作行为中含有异步操作:
比如向后台发送请求获取数据,就需要使用action的dispatch去完成了。
其他使用commit即可。

commit => mutations,用来触发同步操作的方法。
dispatch =>actions,用来触发异步操作的方法。
在store中注册了mutation和action,在组件中用dispatch调用action,然后action用commit调用mutation。

实战

  • this.$store.commit()
import Vue from "vue";
import Vuex from "vuex";
 
Vue.use(Vuex);
 
export const store = new Vuex.Store({
  // state专门用来保存 共享的状态值
  state: {
    // 保存登录状态
    login: false
  },
  // mutations: 专门书写方法,用来更新 state 中的值
  mutations: {
    // 登录
    doLogin(state) {
      state.login = true;
    },
    // 退出
    doLogout(state) {
      state.login = false;
    }
  }
});
<script>
// 使用vux的 mapState需要引入
import { mapState } from "vuex";
 
export default {
  // 官方推荐: 给组件起个名字, 便于报错时的提示
  name: "Header",
  // 引入vuex 的 store 中的state值, 必须在计算属性中书写!
  computed: {
    // mapState辅助函数, 可以快速引入store中的值
    // 此处的login代表,  store文件中的 state 中的 login, 登录状态
    ...mapState(["login"])
  },
  methods: {
    logout() {
      this.$store.commit("doLogout");
    }
  }
};
</script>


<script>
export default {
  name: "Login",
  data() {
    return {
      uname: "",
      upwd: ""
    };
  },
  methods: {
    doLogin() {
      console.log(this.uname, this.upwd);
      let data={
        uname:this.uname,
        upwd:this.upwd
      }
       this.axios
        .post("user_login.php", data)
        .then(res => {
          console.log(res);
          let code = res.data.code;
 
          if (code == 1) {
            alert("恭喜您, 登录成功! 即将跳转到首页");
 
            // 路由跳转指定页面
            this.$router.push({ path: "/" });
 
            //更新 vuex 的 state的值, 必须通过 mutations 提供的方法才可以
            // 通过 commit('方法名') 就可以出发 mutations 中的指定方法
            this.$store.commit("doLogin");
          } else {
            alert("很遗憾, 登陆失败!");
          }
        })
        .catch(err => {
          console.error(err);
        });
    }
 
  }
};
</script>
  • this.$store.dispatch()
toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}
const actions = {
  // user login
  login({ commit }, userInfo){
    const { username, password,useraccount} = userInfo;
    return new Promise((resolve, reject) => {
      login(({userName:username,userAccount:useraccount,userPassword:password})).then(response=>{
        const data=response;
        commit('SET_TOKEN', 1)
        setToken(null)
        commit('SET_ROLES', 1)
        commit('SET_NAME', 1)
        commit('SET_AVATAR', 1)
        commit('SET_INTRODUCTION', 1)
        resolve()
      }).catch(error => {
       reject(error)
      //  debugger;
        //  $Message("密码或账号不对")
     })
    }).catch(error => {
      reject(error)
    })
  }
}

有关vuex中this.$store.commit和this.$store.dispatch的用法的更多相关文章

  1. ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"? - 2

    在Ruby(尤其是Rails)中,您经常需要检查某物是否存在,然后对其执行操作,例如:if@objects.any?puts"Wehavetheseobjects:"@objects.each{|o|puts"hello:#{o}"end这是最短的,一切都很好,但是如果你有@objects.some_association.something.hit_database.process而不是@objects呢?我将不得不在if表达式中重复两次,如果我不知道实现细节并且方法调用很昂贵怎么办?显而易见的选择是创建一个变量,然后测试它,然后处理它,但是你必须想出一个变量名(呃),它也会在内存中

  2. ruby-on-rails - Rails - Carrierwave 进程抛出 ArgumentError : no images in this image list - 2

    在尝试实现应用auto_orient的过程之后!对于我的图片,我收到此错误:ArgumentError(noimagesinthisimagelist):app/uploaders/image_uploader.rb:36:in`fix_exif_rotation'app/controllers/posts_controller.rb:12:in`create'Carrierwave在没有进程的情况下工作正常,但在添加进程后尝试上传图像时抛出错误。流程如下:process:fix_exif_rotationdeffix_exif_rotationmanipulate!do|image|

  3. ruby - 有人可以解释一下在 Ruby 中注入(inject)的真实、通俗易懂的用法吗? - 2

    我正在学习Ruby,遇到了inject。我正处于理解它的风口浪尖,但当我是那种需要真实世界的例子来学习一些东西的人时。我遇到的最常见的例子是人们使用inject来添加一个(1..10)范围的总和,我不太关心这个。这是一个任意的例子。在实际程序中我会用它做什么?我正在学习,所以我可以继续使用Rails,但我不必有一个以Web为中心的示例。我只需要一些我可以全神贯注的目标。谢谢大家。 最佳答案 inject有时可以通过它的“其他”名称reduce更好地理解。它是一个对Enumerable进行操作(迭代一次)并返回单个值的函数。它有许多有

  4. ruby - :this means in Ruby on Rails? 是什么 - 2

    我是Ruby和RubyonRails世界的新手。我已经阅读了一些指南,但我在使用以下语法时遇到了一些麻烦。我认为在Ruby中使用:condition语法来定义具有某种访问器的类属性,例如:classSampleattr_accessor:conditionend隐式声明“条件”属性的getter和setter。当我查看一些Rails示例代码时,我发现以下示例我并不完全理解。例如:@post=Post.find(params[:id])为什么它使用这种语法访问id属性,而不是:@post=Post.find(params[id])或者,例如:@posts=Post.find(:all):

  5. ruby - 使用法拉第上传文件 - 2

    我在尝试使用Faraday将文件上传到网络服务时遇到问题。我的代码:conn=Faraday.new('http://myapi')do|f|f.request:multipartendpayload={:file=>Faraday::UploadIO.new('...','image/jpeg')}conn.post('/',payload)尝试发布后似乎没有任何反应。当我检查响应时this是我所看到的:#:post,:body=>#,#,@opts={}>,#],@index=0>>,#>],@ios=[#,#,@opts={}>,#],@index=0>,#],@index=0>

  6. ruby - rspec: raise_error 用法来匹配错误信息 - 2

    我使用raise(ConfigurationError.new(msg))引发错误我试着用rspec测试一下:expect{Base.configuration.username}.toraise_error(ConfigurationError,message)但这行不通。我该如何测试呢?目标是匹配message。 最佳答案 您可以使用正则表达式匹配错误消息:it{expect{Foo.bar}.toraise_error(NoMethodError,/private/)}这将检查NoMethodError是否由privateme

  7. 【ChatGPT】ChatGPT 的 N 种用法 - 2

    目录ChatGPT简介技术原理应用未来发展ChatGPT的10 种用法ChatGPT简介ChatGPT是一种基于深度学习的大型语言模型,由OpenAI公司开发。技术原理GPT是GenerativePre-trainedTransformer的缩写,意为生成式预训练变压器。它的技术原理是使用了一个基于注意力机制的变压器(Trans

  8. ruby - 无法加载此类文件——脚本/rails : Getting this error while remote debugging through RubyMine - 2

    我在通过RubyMineIDE进行远程调试时遇到以下错误。$bundleexecrdebug-ide--port1234--script/railsserverFastDebugger(ruby-debug-ide0.4.9)listenson:1234/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.12/lib/ruby-debug-ide.rb:123:in`debug_load'/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.

  9. ruby - 是否有 Rack::Session::Cookie 用法的基本示例? - 2

    我找不到任何使用Rack::Session::Cookie的简单示例,并且希望能够将信息存储在cookie中,并在以后的请求中访问它并让它过期.这些是我能找到的唯一示例:HowdoIset/getsessionvarsinaRackapp?http://rack.rubyforge.org/doc/classes/Rack/Session/Cookie.html这是我得到的:useRack::Session::Cookie,:key=>'rack.session',:domain=>'foo.com',:path=>'/',:expire_after=>2592000,:secret=

  10. ruby - Ruby 方法的双冒号(双列或::)语法的惯用用法 - 2

    我是Ruby的新手,发现以下几对令人困惑示例同样有效:File.included_modulesFile::included_modulesFile.stat('mbox')#Returnsa'#'objectFile::stat('mbox')File.new("foo.txt","w")File::new("foo.txt","w")"asdf".size#Aninstancemethod"asdf"::size2+32::send(:+,3)#AnextremeexampleFile::new,尤其是我经常遇到的东西。我的问题:如果我永远避免使用::运算符来限定除类、模块和常量之

随机推荐