zoukankan      html  css  js  c++  java
  • vuex

    首先先正经的来一段官网的"忠告":

    vuex需要遵守的规则:

    一、应用层级的状态应该集中到单个 store 对象中。

    二、提交 mutation 是更改状态的唯一方法,并且这个过程是同步的。

    三、异步逻辑都应该封装到 action 里面。

    文件目录结构

    文件之间的关系:

    store文件夹 - 存放vuex的系列文件

    store.js - 引入vuex,设置state状态数据,引入getter、mutation和action

    getter.js - 获取store内的状态

    mutation.js - 更改store中状态用的函数的存储之地

    action.js - 提交mutation以达到委婉地修改state状态,可异步操作

     

    简单而又普通的写法

    store.js文件:

    import Vue from 'vue'
    
    import Vuex from 'vuex'
    
    import actions from './actions'
    
    import mutations from './mutations'
    
    Vue.use(Vuex)
    
    const state = {
    
        a: '初始值',
    
        b: 'balabala...'
    
    }
    
    export default new Vuex.Store({
    
            state,
    
            actions,
    
            mutations
    
    })

    main.js文件中(从根组件注入store,就像注入router一样):

    通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。

    import store from './store/index'
    
    new Vue({
    
        el: '#app',
    
        router,
    
        store,
    
        ...
    
    })

    Getter.js 的简单配置( store 的计算属性,接受state为参数)

    export default {
            doneTodos: state = >{
                return state.todos.filter(todo = >todo.done)
            }
    }

    获取(某组件的计算属性内部):

    computed: {
    
        doneTodosCount () { 
            return this.$store.getters.doneTodosCount 
        }
    
    }

    可传参的getter属性的简单配置

    export default{
    
        getTodoById: (state) => (id) => { 
            return state.todos.find(todo => todo.id === id) 
        }
    }

    获取(某组件的计算属性内部):

    computed: {
    
        getTodoById() { 
            return this.$store.getters.getTodoById(‘参数’)
        }
    
    }

    mutation.js简单配置:

    export default {
    
            increment(state) {
    
                //变更状态
                state.count++
    
            }
    
    }

    触发(组件中)

    this.$store.commit(state,payload)

    actions.js简单配置:

    export default{
    
        action (context) {
    
        //异步操作
    
            setTimeout(()=>{
    
                //变更状态
    
                context.commit('mutationFunName',value)
    
            })
    
        }
    
    }

    触发(组件的)

    this.$store.dispatch('mutationFunctionName')

     2018-04-07  18:13:34

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    基于分布式锁解决定时任务重复问题
    基于Redis的Setnx实现分布式锁
    基于数据库悲观锁的分布式锁
    使用锁解决电商中的超卖
  • 原文地址:https://www.cnblogs.com/padding1015/p/8734077.html
Copyright © 2011-2022 走看看