目录
2.创建store模块,分别维护state/actions/mutations/getters
3.在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
4.在main.js中导入并使用store实例(只需标红部分)
为什么要用
解决了前端组件传参的问题,针对当前项目所有的变量进行统一管理
组件传参
1.子传父 $emit 父传子 props
2.总线 vue根实例中定义变量,这个变量也是vue实例
3.核心组件vuex
state.js 存储变量
获取this.$store.state.变量值
Getters.js 获取变量值
获取 this.$store.getters.变量的get方法
mutations.js 改变变量值 (同步)
改变值 this.$store.conmmit("同步的方法",{...});
actions.js 改变变量值(异步)
改变值 this.$store.dispath("异步的方法",{...})
1.加载依赖
2.导入Vuex的核心组件,然后index.js加载进来
3.将vuex对应的index.js 挂在到main.js中的vue实例中
4.测试vuex的存储变量的功能
//安装最新版本
npm install vuex -S
//安装指定版本
npm i -S vuex@3.6.2

- import Vue from 'vue'
- import Vuex from 'vuex'
- import state from './state'
- import getters from './getters'
- import actions from './actions'
- import mutations from './mutations'
- Vue.use(Vuex)
- const store = new Vuex.Store({
- state,
- getters,
- actions,
- mutations
- })
-
- export default store
import store from './store'
new Vue({
el: '#app',
router,
store, //在main.js中导入store实例
components: {
App
},
template: '
', data: {
//自定义的事件总线对象,用于父子组件的通信
Bus: new Vue()
}
})
state.js
- export default{
- resName:'反方向的钟'
- }
VuexPage1.vue
- <template>
- <div>
- <h3>{{msg}}</h3>
- </div>
- </template>
-
- <script>
- export default {
- name: 'VuexPage1',
- data() {
- return {}
- },
- computed: {
- msg() {
- // 不推荐 不安全
- return this.$store.state.resName;
- }
- }
- }
- </script>
router/index.js
import VuexPage1 from '@/views/sys/VuexPage1'
//放在 AppMain 的 children 下
{
path: '/sys/VuexPage1',
name: 'VuexPage1',
component: VuexPage1
}

mutations.js
- export default {
- setResName: (state, payload) => {
- //state对应state.js中的对象
- //payload载荷对应传递的JSON对象
- state.resName = payload.resName;
- }
- }
getters.js
- export default {
- getResName: (state) => {
- return state.resName;
- }
- }
VuexPage1.vue
<button @click="buy">点我啊</button>
- methods: {
- buy() {
- this.$store.commit('setResName', {
- resName: '说好不哭'
- })
- }
- }

点击后效果
VuexPage2.vue
- <template>
- <div>
- <h3>页面2{{msg}}</h3>
- </div>
- </template>
-
- <script>
- export default {
- name: 'VuexPage2',
- data() {
- return {}
- },
- computed: {
- msg() {
- return this.$store.getters.getResName;
- }
- }
- }
- </script>
-
- <style>
- </style>
VuexPage1.vue
<button @click="buy2">异步</button>
- buy2() {
- this.$store.dispatch('setResNameAsync', {
- resName: '暗号',
- _this: this
- })
- }

actions.js
- export default {
- setResNameAsync: (context, payload) => {
- //异步修改值 设置执行时间 context值得是vue的上下文 相当于this.$store
- setTimeout(function() {
- context.commit('setResName', payload);
- }, 6000);
- let _this = payload._this;
- let url = _this.axios.urls.SYSTEM_MENU_TREE;
- console.log(url);
- _this.axios.post(url, {}).then(res => {
- console.log(res);
- // this.menus=res.data.result;
- }).catch(function(error) {
- console.log(error);
- });
-
- }
- }

先点的后执行,后点的先执行


先点的执行后

