zoukankan      html  css  js  c++  java
  • Vuex

    专为Vue.js应用程序开发的状态(data里的变量)管理模式,更好的帮助我们在组件外部统一管理状态。

    State 唯一的数据源,每个data里的变量

    const Counter = {
        template: '<div>{{count}}</div>',
        computed: {
            count() {
                return this.$store.state.count
            }
        }
    }

    Getters 可以派生出一些新的状态

    const store = new Vuex.Store({
        state: {
            todos: [
                {id: 1, text: '...', done: true},
                {id: 1, text: '...', done: false}
            ]
        },
        getters: {
            doneTodos: state => {
                return state.todos.filter(todo => todo.done)//获取done为true的数据
            }
        }
    })

    Mutations 唯一可以提交和改变状态,更改store

    const store = new Vuex.Store({
        state: {
            count: 1
        },
        mutations: {
            increment(state) {
                //变更状态
                state.count++;
            }
        }
    })
    //调用
    store.commit('increment')

    Actions 提交的是Mutation,而不是直接变更状态,可以包含任意异步操作

    const store = new Vuex.Store({
        state: {
            count: 1
        },
        mutations: {
            increment(state) {
                //变更状态
                state.count++;
            }
        },
        actions:{
            increment(context){
                context.comit('increment')
            }
        }
    })

    Modules
    当管理的状态比较多时,需要将strore对象分割成模块

    状态管理模式

    // 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        increment (state,n) {
          //变更状态
          state.count+=n;
        }
      }
    })
    
    //唤醒 mutation handler(回调函数)
    store.commit('increment',10)
    
    store.commit({
      type: 'increment',
      amount: 10
    })

    通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更

    router里获取和改变vuex的值

    router.app.$options.store.state.nickName
    router.app.$options.store.commit('updataLoginModalFlag',true);
  • 相关阅读:
    164.Maximum Gap
    163.Missing Ranges
    162.Find Peak Element
    161.One Edit Distance
    160.Intersection of Two Linked Lists
    7.5爬取猫眼Top100电影名单
    7.5文件操作
    7.4文件操作(1)
    7.4一个失败的网易云爬虫,
    7.3数据结构(1)
  • 原文地址:https://www.cnblogs.com/conglvse/p/9521925.html
Copyright © 2011-2022 走看看