vue cli大型项目调用vuex状态管理

1、安装

使用vue-cli搭建好项目以后,安装vuex npm install vuex –save-dev

2、创建Vuex.Store实例

文件夹目录如下:

main.js入口文件

import store from './store'
 
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

store/index.js:

import Vue from 'vue';
import Vuex from 'vuex';
 
import state from './state.js';
import getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';
import modules from './module/modules.js';
 
Vue.use(Vuex);
 
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules
});
 
export default store;

store/state.js

const state = {
  count: 0,
  number: 0,
  username: 'liu',
  nickname: 'never',
  password: 123
};
 
export default state;

store/getters.js

const getters = {
  message: state => {
    return '用户名为:' + state.username;
  },
  msg: state => {
    return `昵称为:${state.nickname}`;
    // 等价于  return '昵称为:' + state.nickname;
    // `${}` 是ES6中的模版字符串语法
  }
};
 
export default getters;

store/mutations.js

const mutations = {
  //同步增加
  increment: state => {
    state.count++;
  },
  //异步增加
  asnyAdd: state => {
    state.number++;
  },
  changePassword: (state, payload) => {
    state.password = payload.password;
  },
  changeNickname: (state, payload) => {
    state.nickname = payload.nickname;
  }
};
 
export default mutations;

store/actions.js

const actions = {
  asnyAdd: context => {
    context.commit('asnyAdd');
  },
  changeNickname ({commit}, payload) {
    commit('changeNickname', payload);
  }
};
 
export default actions;

页面调用、修改状态

<template>
	<div class="indexDemo">
		<h1>{{study}}</h1>
 
    <button @click="increment">同步加1</button>
    <button @click="asnyAdd1">异步加1</button>
 
    <button @click="changePassword({password: 123456})">同步修改密码</button>
    <button @click="changeNickname({nickname: 'sleepwalker'})">异步修改昵称</button>
 
    <p>count:{{count}}</p>
    <p>number:{{number}}</p>
    <p>username:{{username}}</p>
    <p>nickname:{{nickname}}</p>
    <p>password:{{password}}</p>
 
    <p>{{message}}</p>
    <p>{{msg}}</p>
	</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex';
export default {
	name:'helloworld',
	data() {
		return {
			study: 'vuex-study'
		}
	},
	computed: {
    ...mapState(['count', 'number', 'username', 'nickname', 'password']),
    ...mapGetters(['message', 'msg'])
  },
	created(){ 
 
  },
  methods:{
		...mapMutations(['increment', 'changePassword']),
    // ...mapActions(['asnyAdd', 'changeNickname'])
    //同上
    ...mapActions({
      asnyAdd1:'asnyAdd',
      changeNickname:'changeNickname'
    })
	},
	watch:{
 
	},
 
}
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值