vuex入门

引用 https://segmentfault.com/a/1190000009404727?utm_source=tag-newest

1、安装
npm install vuex --save

2、main.js 中引入

import vuex from 'vuex'
Vue.use(vuex);
var store = new vuex.Store({//store对象
    state:{
        show:false
    }
})

3、 在实例化 Vue对象时加入 store 对象

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

4、在 src 目录下 , 新建一个 store 文件夹 , 然后在里面新建一个 index.js :

import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);

export default new vuex.Store({
    state:{
        show:false
    }
})

5、


mapState、mapGetters、mapActions

有时store.state.dialog.show 、store.dispatch('switch_dialog') 这种写法很冗长 , 不方便 , 我们没使用 vuex 的时候 , 获取一个状态只需要 this.show , 执行一个方法只需要 this.switch_dialog 就行了 , 使用 vuex 使写法变复杂了 ?
使用 mapState、mapGetters、mapActions 就不会这么复杂了
以 mapState 为例 :

<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>

<script>
import {mapState} from 'vuex';
export default {
  computed:{
    //这里的三点叫做 : 扩展运算符
    ...mapState({
      show:state=>state.dialog.show
    }),
  }
}
</script>

等于

<template>
  <el-dialog :visible.sync="show"></el-dialog>
</template>

<script>
import {mapState} from 'vuex';
export default {
  computed:{
    show(){
        return this.$store.state.dialog.show;
    }
  }
}
</script>

注:mapGetters、mapActions 和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods 中。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • vuex最简单、最详细的入门文档 vuex最简单、最详细的入门文档 如果你在使用 vue.js , 那么我想你可能...
    MJ_e9a5阅读 677评论 0 7
  • 如果你在使用 vue.js , 那么我想你可能会对 vue 组件之间的通信感到崩溃 。 我在使用基于 vue.js...
    笑得好傻阅读 364评论 0 10
  • vuex 入门随记 首先肯定是要安装vuex 这里我们使用npm包管理工具进行安装 npm install vue...
    Yhong_阅读 411评论 0 2
  • 1. 简述 VUEX网上有不少教程,我也看了官方和不少博客的教程,但是还是看的不爽,因为总是用全局的写法,而实际...
    点_ba7a阅读 1,407评论 0 3
  • 如果你在使用 vue.js , 那么我想你可能会对 vue 组件之间的通信感到崩溃 。 我在使用基于 vue.js...
    BrightenSun阅读 5,317评论 6 21