为什么使用vuex?

vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值(兄弟组件下又有父子组件),或者大型spa单页面框架项目,页面多并且一层嵌套一层的传值,异常麻烦,用vuex来维护共有的状态或数据会显得得心应手。

需求:两个组件A和B,vuex维护的公共数据是 餐馆的名称 resturantName,默认餐馆名称是 飞歌餐馆,那么现在A和B页面显示的就是飞歌餐馆。如果A修改餐馆名称 为 A餐馆,则B页面显示的将会是 A餐馆,反之B修改同理。这就是vuex维护公共状态或数据的魅力,在一个地方修改了数据,在这个项目的其他页面都会变成这个数据。

一、使用 vue-cli脚手架工具创建一个工程项目,工程目录,创建组件A和组件B路由如下

路由如下:

  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import componentsA from '@/components/componentsA'
  4. import componentsB from '@/components/componentsB'
  5.  
  6. Vue.use(Router)
  7.  
  8. export default new Router({
  9. mode: 'history',
  10. routes: [
  11. {
  12. path: '/',
  13. name: 'componentsA',
  14. component: componentsA
  15. },
  16. {
  17. path: '/componentsA',
  18. name: 'componentsA',
  19. component: componentsA
  20. },
  21. {
  22. path: '/componentsB',
  23. name: 'componentsB',
  24. component: componentsB
  25. }
  26. ]
  27.  
  28. })

app.vue

  1. <template>
  2. <div id="app">
  3. <router-view/>
  4. </div>
  5. </template>
  6.  
  7. <script>
  8. export default {
  9. name: 'App'
  10. }
  11. </script>
  12.  
  13. <style>
  14. #app {
  15. font-family: 'Avenir', Helvetica, Arial, sans-serif;
  16. -webkit-font-smoothing: antialiased;
  17. -moz-osx-font-smoothing: grayscale;
  18. text-align: center;
  19. color: #2c3e50;
  20. margin-top: 60px;
  21. }
  22. </style>

二、开始使用vuex,新建一个 sotre文件夹,分开维护 actions mutations getters

1、在store/index.js文件中新建vuex 的store实例

*as的意思是 导入这个文件里面的所有内容,就不用一个个实例来导入了。

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import * as getters from './getters' // 导入响应的模块,*相当于引入了这个组件下所有导出的事例
  4. import * as actions from './actions'
  5. import * as mutations from './mutations'
  6.  
  7. Vue.use(Vuex)
  8. // 首先声明一个需要全局维护的状态 state,比如 我这里举例的resturantName
  9. const state = {
  10. resturantName: '飞歌餐馆' // 默认值
  11. // id: xxx 如果还有全局状态也可以在这里添加
  12. // name:xxx
  13. }
  14.  
  15. // 注册上面引入的各大模块
  16. const store = new Vuex.Store({
  17. state, // 共同维护的一个状态,state里面可以是很多个全局状态
  18. getters, // 获取数据并渲染
  19. actions, // 数据的异步操作
  20. mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
  21. })
  22.  
  23. export default store // 导出store并在 main.js中引用注册。

2、actions

  1. // 给action注册事件处理函数。当这个函数被触发时候,将状态提交到mutations中处理
  2. export function modifyAName({commit}, name) { // commit 提交;name即为点击后传递过来的参数,此时是 'A餐馆'
  3. return commit ('modifyAName', name)
  4. }
  5. export function modifyBName({commit}, name) {
  6. return commit ('modifyBName', name)
  7. }
  8.  
  9. // ES6精简写法
  10. // export const modifyAName = ({commit},name) => commit('modifyAName', name)

3.mutations

  1. // 提交 mutations是更改Vuex状态的唯一合法方法
  2. export const modifyAName = (state, name) => { // A组件点击更改餐馆名称为 A餐馆
  3. state.resturantName = name // 把方法传递过来的参数,赋值给state中的resturantName
  4. }
  5. export const modifyBName = (state, name) => { // B组件点击更改餐馆名称为 B餐馆
  6. state.resturantName = name
  7. }

4.getters

  1. // 获取最终的状态信息
  2. export const resturantName = state => state.resturantName

三、在main.js中导入 store实例

  1. // The Vue build version to load with the `import` command
  2. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
  3. import Vue from 'vue'
  4. import App from './App'
  5. import router from './router'
  6. import store from './store'
  7.  
  8. Vue.config.productionTip = false
  9.  
  10. /* eslint-disable no-new */
  11. new Vue({
  12. el: '#app',
  13. router,
  14. store, // 这样就能全局使用vuex了
  15. components: { App },
  16. template: '<App/>'
  17. })

四、在组件中使用

...mapactions 和 ...mapgetters都是vuex提供的语法糖,在底层已经封装好了,拿来就能用,简化了很多操作。

其中...mapActions(['clickAFn']) 相当于this.$store.dispatch('clickAFn',{参数}),mapActions中只需要指定方法名即可,参数省略。

...mapGetters(['resturantName'])相当于this.$store.getters.resturantName

1.在组件A中定义点击事件,点击 修改 餐馆的名称,并把餐馆的名称在事件中用参数进行传递。

  1. <template>
  2. <div class="componentsA">
  3. <P class="title">组件A</P>
  4. <P class="titleName">餐馆名称:{{resturantName}}</P>
  5. <div>
  6. <!-- 点击修改 为 A 餐馆 -->
  7. <button class="btn" @click="modifyAName('A餐馆')">修改为A餐馆</button>
  8. </div>
  9. <div class="marTop">
  10. <button class="btn" @click="trunToB">跳转到B页面</button>
  11. </div>
  12. </div>
  13. </template>
  14.  
  15. <script>
  16. import {mapActions, mapGetters} from 'vuex'
  17. export default {
  18. name: 'A',
  19. data () {
  20. return {
  21. }
  22. },
  23. methods:{
  24. ...mapActions( // 语法糖
  25. ['modifyAName'] // 相当于this.$store.dispatch('modifyName'),提交这个方法
  26. ),
  27. trunToB () {
  28. this.$router.push({path: '/componentsB'}) // 路由跳转到B
  29. }
  30. },
  31. computed: {
  32. ...mapGetters(['resturantName']) // 动态计算属性,相当于this.$store.getters.resturantName
  33. }
  34. }
  35. </script>
  36.  
  37. <!-- Add "scoped" attribute to limit CSS to this component only -->
  38. <style scoped>
  39. .title,.titleName{
  40. color: blue;
  41. font-size: 20px;
  42. }
  43. .btn{
  44. width: 160px;
  45. height: 40px;
  46. background-color: blue;
  47. border: none;
  48. outline: none;
  49. color: #ffffff;
  50. border-radius: 4px;
  51. }
  52. .marTop{
  53. margin-top: 20px;
  54. }
  55. </style>

2.B组件同理

  1. <template>
  2. <div class="componentsB">
  3. <P class="title">组件B</P>
  4. <P class="titleName">餐馆名称:{{resturantName}}</P>
  5. <div>
  6. <!-- 点击修改 为 B 餐馆 -->
  7. <button class="btn" @click="modifyBName('B餐馆')">修改为B餐馆</button>
  8. </div>
  9. <div class="marTop">
  10. <button class="btn" @click="trunToA">跳转到A页面</button>
  11. </div>
  12. </div>
  13. </template>
  14.  
  15. <script>
  16. import {mapActions, mapGetters} from 'vuex'
  17. export default {
  18. name: 'B',
  19. data () {
  20. return {
  21. }
  22. },
  23. methods:{
  24. ...mapActions( // 语法糖
  25. ['modifyBName'] // 相当于this.$store.dispatch('modifyName'),提交这个方法
  26. ),
  27. trunToA () {
  28. this.$router.push({path: '/componentsA'}) // 路由跳转到A
  29. }
  30. },
  31. computed: {
  32. ...mapGetters(['resturantName']) // 动态计算属性,相当于this.$store.getters.resturantName
  33. }
  34. }
  35. </script>
  36.  
  37. <!-- Add "scoped" attribute to limit CSS to this component only -->
  38. <style scoped>
  39. .title,.titleName{
  40. color: red;
  41. font-size: 20px;
  42. }
  43. .btn{
  44. width: 160px;
  45. height: 40px;
  46. background-color: red;
  47. border: none;
  48. outline: none;
  49. color: #ffffff;
  50. border-radius: 4px;
  51. }
  52. .marTop{
  53. margin-top: 20px;
  54. }
  55. </style>

出处:https://blog.csdn.net/qq_35430000/article/details/79412664

感谢原创博主:飞歌Fly

vuex的配置使用的更多相关文章

  1. vuex目录配置

    vuex目录配置,即vue-cli开发时目录配置 项目结构 Vuex 并不限制你的代码结构.但是,它规定了一些需要遵守的规则: 应用层级的状态应该集中到单个 store 对象中. 提交 mutatio ...

  2. 如何在vue-cli中使用vuex(配置成功

    前言 众所周知,vuex 是一个专为 vue.js 应用程序开发的状态管理模式,在构建一个中大型单页应用中使用vuex可以帮助我们更好地在组件外部管理状态.而vue-cli是vue的官方脚手架,它能帮 ...

  3. Vue+webpack项目配置便于维护的目录结构

    新建项目的时候创建合理的目录结构便于后期的维护是很重要 环境:vue.webpack 目录结构: 项目子目录结构 子目录结构都差不多,主要目录是在src下面操作 src目录结构 src/common ...

  4. Vue核心技术 Vue+Vue-Router+Vuex+SSR实战精讲

    第1章 课程介绍课程介绍,介绍课程的章节安排和学习本门课程的一些注意点.1-1 课程导学 试看1-2 项目介绍1-3 Webpack4升级注意 第2章 Vue+Webpack的前端工程工作流搭建详细讲 ...

  5. Vue 状态管理 Vuex

    1.概述 Vuex作为插件,管理和维护整个项目的组件状态. 2.安装vuex cnpm i --save vuex 3.vuex使用 github地址:https://github.com/MengF ...

  6. vuex mapActions

    在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用( ...

  7. vuex mapMutations 使用

    你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit ...

  8. vuex mapGetters

    1.vuex 配置 //vuex的配置 //注意Store是大写 const store = new Vuex.Store({ //数据保存 state: { show: false, count: ...

  9. 用vuex写了一个购物车H5页面的示例代码

    用vuex写了一个购物车H5页面的示例代码:https://www.jb51.net/article/152008.htm 通过购物车的一个案列,把vuex学习了一篇. vuex概念浅谈 Vuex 是 ...

随机推荐

  1. win7 开机,或重启自动启动 该文件下的

    win7 开机,或重启自动启动 该文件下的: 把桌面上快捷键放入文件内就行 C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start ...

  2. .HDF数据库与SQLSERVER / ORACLE的区别

    无论ArcGIS的.gbd文件还是MapGIS的.hdf文件,都是数据库文件. 后缀是无意义的.有意义的是其中内在的逻辑和数据结构. https://zhidao.baidu.com/question ...

  3. save change is not permitted

    https://support.microsoft.com/en-my/help/956176/error-message-when-you-try-to-save-a-table-in-sql-se ...

  4. IntelliJ IDEA中创建xml文件

      1.file—setting,左上角输入template, 2.在左侧栏找到File And Code Templates 3.中间选中Files 4.点击+号,添加模板 5.输入模板名字:Nam ...

  5. 小程序页面间传值(处理传值为对象,简单传值直接用options.XX的形式获取)

    bookgoods:function(){ var Json = JSON.stringify(this.data.goods) wx.navigateTo({ url: '/pages/bookgo ...

  6. spring4.1.8扩展实战之六:注册bean到spring容器(BeanDefinitionRegistryPostProcessor接口)

    本章是<spring4.1.8扩展实战>系列的第六篇,目标是学习如何通过自己写代码的方式,向spring容器中注册bean: 原文地址:https://blog.csdn.net/boli ...

  7. ICPC2019上海区域赛 部分题解(正在更新)

    K. Color Graph 题意: 给定一个简单图,点个数<=16,删去部分边后,使得该图中无边数为奇数得环,问剩下的边数最大为多少? 思路: 如果一个图中无奇数边的环,那么这个图一定是个二分 ...

  8. jmeter设置全局变量token

    返回登录后的token使用json path Extractor插件,定位到获取后的token为变量 在登录下后置处理器下添加json path Extracto插件 根据上面获取到的token位置路 ...

  9. 【报错】An error happened during template parsing (template: "class path resource [templates/adminManageCourse.html]")

    页面显示: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing t ...

  10. dpkg:处理软件包 xxx (--configure)时出错

    9月 17 16:11:35 xiakaibi-PC systemd[1]: Starting LSB: Start Jenkins at boot time...9月 17 16:11:35 xia ...