11.Vuex

简介: 11.Vuex

1.介绍

1.1.Vuex是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。

1.2. 什么是“状态管理模式”?

这个状态自管理应用包含以下几个部分:

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

2.使用

2.1.安装

npm i -S vuex@3.6.2

2.2.创建store文件夹,创建文件

创建好如下图所示

2.3.在src/store/index.js中写入内容

新建vuex的store实例,并注册上面引入的各大模块

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

2.4.在src/main.js中导入并使用store实例

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from '@/api/http'
import VueAxios from 'vue-axios'
import router from './router'
import store from './store'
//开发环境下才会引入mockjs
process.env.MOCK && require('@/mock')
Vue.use(ElementUI);
Vue.use(VueAxios,axios)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  data(){
    return{
      Bus: new Vue({})
    }
  },
  router,
  store,
  components: { App },
  template: '<App/>'
})

2.5.在views新建vuex目录,添加Page1.vue和Page2.vue文件

Page1.vue

<template>
  <div>
    <h1>这是页面1</h1>
  </div>
</template>
<script>
export default {
  name: "Page1"
}
</script>
<style scoped>
</style>

Page2.vue

<template>
  <div>
    <h1>这是页面2</h1>
  </div>
</template>
<script>
export default {
  name: "Page1"
}
</script>
<style scoped>
</style>

2.6.配置路由

修改src/router/index.js

import Page1 from '@/views/vuex/Page1'
import Page2 from '@/views/vuex/Page2'
#添加到与TopNav同级的地方
{
    path: '/vuex/Page1',
  name: 'Page1',
  component: Page1
},{
    path: '/vuex/Page2',
  name: 'Page2',
  component: Page2
}

2.7.修改components/LeftNav.vue

=====仅展示部分内容
<el-menu
    router :default-active="$route.path"
    default-active="2" class="el-menu-vertical-demo" background-color="#334157"
           text-color="#fff" active-text-color="#ffd04b" :collapse="collapsed">
    <!-- <el-menu default-active="2" :collapse="collapsed" collapse-transition router :default-active="$route.path" unique-opened class="el-menu-vertical-demo" background-color="#334157" text-color="#fff" active-text-color="#ffd04b"> -->
    <div class="logobox">
      <img class="logoimg" src="../assets/img/logo.png" alt="">
    </div>
    
    ///======添加的内容
    <el-menu-item
      index="/vuex/Page1"
      key="'key_999">
      <span>Vuex页面1</span>
    </el-menu-item>
    <el-menu-item
      index="/vuex/Page2"
      key="'key_1000">
      <span>Vuex页面2</span>
    </el-menu-item>

此时应该出现的效果

3.实例

3.1.修改src/store/state.js

export default {
  name: 'Vuex学习'
}

3.2.取值

3.2.1.state直接取值

修改src/views/vuex/Page1.vue的内容

<template>
  <div>
    <h1>这是页面1========{{msg}}</h1>
    <p>state直接取值</p>
    <button @click="func1">state直接取值</button>
  </div>
</template>
<script>
export default {
  name: "Page1",
  data(){
    return{
      msg: null
    }
  },
  methods:{
    func1(){
      this.msg = this.$store.state.name;
    }
  }
}
</script>
<style scoped>
</style>

效果

3.2.2.getters取值

1.修改src/store/getters.js中的值

export default {
  getName(state){
    return state.name;
  }
}

2.修改Page1.vue的内容

#div中添加
<p>getters取值</p>
<button @click="func2">getters取值</button>
#methods中添加
func2(){
  this.msg = this.$store.getters.getName;
}

3.效果

3.3.存值

3.3.1.mutations存值

1.修改mutations.js的内容

export default {
  setName(state, payload) {
    state.name = payload.name;
  }
}

2.修改Page1.vue

#div中添加
<p>mutations存值</p>
<button @click="func3">mutations存值</button>
#methdos中添加
func3(){
  this.$store.commit('setName',{
    name: '这是修改后的Vuex学习'
  });
}

3.修改Page2.vue

<template>
  <div>
    <h1>这是页面2===={{msg}}</h1>
  </div>
</template>
<script>
export default {
  name: "Page2",
  data(){
    return{
      msg: null
    }
  },created() {
    this.msg = this.$store.state.name;
  }
}
</script>
<style scoped>
</style>

3.效果

3.3.2.actions存值

1.修改Page1.vue的内容,删除data中的msg,改为computed属性

computed:{
    msg(){
        return this.$store.state.name;
    }
}

2.修改store/actions.js

export default {
  setNameAsync(context, payload) {
    //context指的是vuex的实例
    //等价于this.$store
    setTimeout(function () {
      context.commit('setName',payload);
    },6000)
  }
}

3.修改Page1.vue

#div中添加
<p>actions存值</p>
<button @click="func4">actions存值</button>
#methods中添加
func4(){
  this.$store.dispatch('setNameAsync',{
    name: '这是修改后的Vuex学习--action'
  });
}

效果

异步修改值

3.4.发送ajax请求获取后台数据

1.修改api/action.js

'VUEX_INFO': '/vuex/queryVuex',//vuex异步获取数据

2.修改Page1.vue

#div中添加
<p>后台ajax改变值</p>
<button @click="func5">后台ajax改变值</button>
#methods中添加
func5(){
      this.$store.dispatch('setNameAjax',{
        _this: this
      });
    }

3.修改actions.js

export default {
  setNameAsync(context, payload) {
    //context指的是vuex的实例
    //等价于this.$store
    setTimeout(function () {
      context.commit('setName', payload);
    }, 3000)
  },
  setNameAjax(context, payload) {
    let _this = payload._this;
    let url = _this.axios.urls.VUEX_INFO;
    let params = {
      resturantName: '这是ajax的修改'
    }
    _this.axios.get(url, {params}).then(resp=>{
      if(resp.data.success){
        context.commit('setName',{
          name: resp.data.msg
        })
      }
    }).catch(err=>{
    })
  }
}

4.效果

目录
相关文章
|
3月前
|
存储 JavaScript
|
4月前
|
存储 JavaScript 前端开发
vuex使用
vuex使用
|
4月前
|
存储 JavaScript API
vuex的使用
vuex的使用
26 0
|
存储 资源调度 JavaScript
Vuex详解,详细讲解一下Vuex
Vuex详解,详细讲解一下Vuex
198 0
|
4月前
|
存储 JavaScript
什么是vuex
什么是vuex
36 0
|
9月前
vuex
vuex
42 0
|
存储 JavaScript
关于Vuex的简单实际应用
关于Vuex的简单实际应用
关于Vuex的简单实际应用
|
JavaScript 调度
浅谈Vuex的使用
浅谈Vuex的使用
101 0
浅谈Vuex的使用
|
存储 缓存 资源调度
Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
Vuex