vuex

 


  1. 下载 vuex
  • vue init webpack vue-vuex 创建vuex项目
  • cnpm install 安装依赖
  • cnpm install vuex --save 安装vuex包

  1. 引入vuex
  • import Vuex from 'vuex' 引入vuex插件
  • Vue.use(Vuex) 使用vuex插件

  1. 使用
  • 在scr文件夹下 --> 新建store文件夹 --> 新建index.js文件
  • import Vue from 'vue'
  • import Vuex from 'vuex'
  • Vue.use(Vuex)
  • export default new Vuex.Store({ }) 暴露出一根vuex对象
  • import store from './store' 必须在main.js中引入store,系统会自动寻找index.js文件
  • 在main.js中的 new vue({store})实例中加入store

  1. export default new Vuex.Store({ });store的构成
  • state 状态(数据)
  • mutations 定义方法,(同步的)改变 state 中的值
  • actions 行为,(异步的)触发 mutations 中的事件,从而改变 state 的值
  • getters 在state基础上派生出来的值
  • modules 模块(state的缩小版)

(1)STATE

  • this.$store.state.val

在main.js引入store并且在new Vue({})实例中添加store后,在全局都可以调用store

eg:

  • 在index中引入vuex、store
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    const state = {  // 
        val: '1234'
    }
    
    export default new Vuex.Store({
        state
    })

 

  • 在子组件中调用store中的state
    <template>
        <div>
            <div>组件D --> 接收B数据 {{value}}</div>
        </div>
    </template>
    
    <script>
    export default {
        computed: {
            value() {
                return this.$store.state.val  // 调用store中的state
            }
        }
    }
    </script>

 

(1.2) mapMutations 辅助函数

  • 通过mapMutations来获得state的值
    <template>
        <div>
            <div>组件D --> 接收state数据 {{value}}</div>
        </div>
    </template>
    
    <script>
    import {mapState} from 'Vuex'
    export default {
        computed: {
            ...mapState({
                value: state => state.val
            })
        }
    }
    </script>

 


(2)MUTATION改变store中状态的唯一方法

  • 通过 commit 来触发 mutation 中定义的函数
  • 注意 mutation 中只能定义同步函数
  • this.$store.commit('setVal',value)

eg:

  • 在index.js中定义setVal方法
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    // console.log(Vuex)
    const state = {
        val: '1234'
    }
    const mutations = {
        setVal(state,value) {
            state.val = value;
        }
    }
    
    export default new Vuex.Store({
        state,
        mutations
    })

 

  • 在组件中调用setVal方法,改变state的数据
    <template>
        <div>
            <div>组件E数据{{value}}</div>
            <input type="text" v-model='value'>
        </div>
    </template>
    <script>
    export default {
        data() {
            return {
                value:''
            }
        },
        watch: {
            value() {
                this.$store.commit('setVal',this.value) // 通过commit触发setVal来改变state的数据
            }
        }
    }
    </script>

 

**(2.2)**mapMutations 辅助函数

  • 通过mapMutations来获取mutations中的方法
    <template>
        <div>
            <div>组件E数据{{value}}</div>
            <input type="text" v-model='value'>
        </div>
    </template>
    <script>
    import {mapMutations} from 'vuex'
    export default {
        data() {
            return {
                value:''
            }
        },
        methods: {
            ...mapMutations(['setVal'])
        },
        watch: {
            value() {
                this.setVal(this.value)
            }
        }
    }
    </script>

 

  • 如果想给函数起个别名
    methods: {
        ...mapMutations({
            setValue: 'setVal'
        })
    }

 


(3)ACTIONS 通过异步的触发mutation中的函数来改变state中的值

  • 通过dispatch来触发actions
  • this.$store.dispatch('asynSetValue',value)

eg:

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    const state = {
        val: '1234'
    }
    const mutations = {
        setVal(state,value) {
            state.val = value;
        }
    }
    const actions = {
        asynSetValue(ctx,value) { // ctx
            setTimeout(function () {
                ctx.commit('setVal',value)  // ctx可以看作为store的镜像
            }, Math.random()*500)
        }
    }
    
    export default new Vuex.Store({
        state,
        mutations,
        actions
    })
    <template>
        <div>
            <div>组件E数据{{value}}</div>
            <input type="text" v-model='value'>
        </div>
    </template>
    <script>
    export default {
        data() {
            return {
                value:''
            }
        },
        watch: {
            value() {
                this.$store.dispatch('asynSetValue',this.value)
            }
        }
    }
    </script>

 

  • 解构的方式
    const actions = {
        asynSetValue({commit},value) { // ctx
            setTimeout(function () {
                commit('setVal',value)
            }, Math.random()*500)
        }
    }

 


(4)GETTERS

  • 对state的值进行处理
  • 取派生值 this.$store.getters.newVal
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    
    const state = {
        val: '1234'
    }
    const mutations = {
        setVal(state,value) {
            state.val = value;
        }
    }
    const getters = {
        newVal(state) {
            return state.val.split('').join(',')
        }
    }
    
    export default new Vuex.Store({
        state,
        mutations,
        getters
    })
    <template>
        <div class="wrapper">
            <div>{{value}}</div>
        </div>
    </template>
    <script>
    export default {
        components: {
            componentE
        },
        computed: {
            value() {
                return this.$store.getters.newVal
            }
        }
    }
    </script>

 

(4.1) mapGetters 辅助函数

  • 获取getters
    <template>
        <div class="wrapper">
            <div>组件C --> 接收getter数据 {{newVal}}</div>
            <component-e></component-e>
        </div>
    </template>
    <script>
    import componentE from './componentE'
    import {mapGetters} from 'Vuex'
    export default {
        components: {
            componentE
        },
        computed: {
            ...mapGetters(['newVal'])
        }
    }
    </script>

 


使用vuex

1. 部署Vuex

  • 在 src 文件夹中新建 store 文件夹,新建 index.js 文件
  • import Vue from 'vue'
  • import Vuex from 'vuex'
  • Vue.use(Vuex)
  • 在 main.js 中引入 store (import store from './store')
  • 在 vue 实例中加入 store

2. Vuex.Store 的构成

export default new Vuex.Store({ <br>
    state, ==》 数据    <br> 
    mutations,  ==》 定义方法,(同步的)改变 state 中的值 <br>
    actions,    ==》行为,(异步的)触发 mutations 中的事件,从而改变 state 的值 <br>
    getters,    ==》 派生值, <br>
    modules: {    ==》 模块 <br>
        a: { <br>
            state, <br>
            mutations, <br>
            actions, <br>
            getters, <br>
            modules <br>
        } <br>
    } <br>
})

 


state

1. 在组件中获得 Vuex 状态 store.state

在组件中,通过 this.$store.state 获得数据
先要在 index.js 中声明一个 state
    const state = {
        val:'1234'   
    }
    computed: {
        val() {
            console.log(this.$store)
            return this.$store.state.val
        }
    }

 

mutation (将值放入到 state 中)

  • 改变 store 中的状态的唯一方法 mutation
  • 通过 commit 来触发 mutation 中定义的函数
  • 注意 mutation 中只能定义同步函数
  • 辅助函数 mapMutations
先定义 mutations 函数
    const mutations = {
        setVal(state, value) {
            state.val = value;
        }
    }

 

在监听函数中
    watch:{
        value(){
            this.$store.commit('setVal',this.value)
        }
    }

 

actions 异步触发 mutation

ctx 可以看成是 store 的镜像,但又不完全一样

    const actions = {
        asynSetValue(ctx, value) {
            setTimeout(()=>{
                ctx.commit('setVal',value)
            }, Math.random() * 3000)
        }
    }
    watch:{
        value(){
            this.$store.dispatch('asynSetValue',this.value)
        }
    }

 


getters 派生值

方法定义
   const getters = {
        newVal(state) {
            return state.val.split('').join(',')
        }
    }

 

输出
  computed:{
        value() {
            return this.$store.getters.newVal
        }
    }

 

取值
    watch:{
        value(){
            this.$store.commit('setVal',this.value)
        }
    }

 


取值: this.$store.state.val

取派生值: this.$store.getters.newVal

触发commit方法来触发setVal函数: this.$store.commit('setVal',value)

触发dispatch方法来触发asynSetValue函数: this.$store.dispatch('asynSetValue',value)

mapState,mapMutations,mapActions,mapGetters 这4中方法对应了上面4中扩展形式


mapState 辅助函数

  • 获取 state 的一种方式

使用之前要在组件中先引入

    import {mapState} from 'Vuex' // 解构的方式引入
    computed: {
        ...mapState({
            val: state => state.val
        })
    }

 

  • 上面的 val 是在 index.js 中定义好的
    const state = {
        val:'1234'   
    }

 


mapMutations

在组件中引入

    import {mapMutations} from 'vuex'
    methods:{
        ...mapMutations(['setVal'])
    },
    watch:{
        value(){
            this.setVal(this.value)
        }
    }

 

mapGetters

  • 引入
import {mapGetters} from 'vuex'

    computed:{
        ...mapGetters({
            newV:'newVal'
        })
    }

 


modules

    modules: {
        map: {
            namespaced: true,
            state: {
                title: '地图',
                url: 'map.baidu.com'
            },
            mutations: {
                updateVal(state, val) {
                    console.log('map');
                    state.title = val
                }
            },
            actions: {
                _updateVal({commit}, val) {
                    commit('updateVal', val) // 这里默认触发的是当前的updateVal, 如果想要触发外面的updateVal需要加上{root:true}字段 commit('updateVal', val{root:true})
                }
            }
        },
        new: {
            state: {
                title: '新闻',
                url: 'new.baidu.com'
            }
        }
    }

 

在 modules 中定义的方法如果跟外面的同名,就会合并(低版本vue会报错);可以使用命名空间,

    methods: {
        ...mapMutations(['updateVal']),
        ...mapActions('map',['_updateVal']) // 使用命名空间之后就要在方法前写上模块名
    }

 

posted @ 2018-07-30 19:44  Goff956  阅读(117)  评论(0编辑  收藏  举报