100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

时间:2023-06-10 12:38:03

相关推荐

vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

this.$store.dispatch()this.$mit()方法的区别总的来说他们只是存取方式的不同,两个方法都是传值给vuex的mutation改变state

this.$store.dispatch():含有异步操作,例如向后台提交数据,写法:this.$store.dispatch(‘action方法名’,值)

this.$mit():同步操作,,写法:this.$mit(‘mutations方法名’,值)

commit: 同步操作

存储this.$mit('changeValue',name)取值this.$store.state.changeValue

dispatch: 异步操作

存储this.$store.dispatch('getlists',name)取值this.$store.getters.getlists

案例:

Vuex文件 src/store/index.js

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;}}});

组件JS部分 : src/components/Header.vue

<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.$mit("doLogout");}}};</script>

组件JS部分 : src/components/Login.vue

<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.$mit("doLogin");} else {alert("很遗憾, 登陆失败!");}}).catch(err => {console.error(err);});}}};</script>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。