Vue.js数据状态管理-Vuex(二)

来源:互联网 发布:剑灵男召唤师捏脸数据 编辑:程序博客网 时间:2024/06/01 07:55

前言

Vuex主要应用于中、大型单页应用的数据状态管理架构。

父子组件的通信

  • 父 -> 子: props
  • 子 -> 父: 自定义event

组件数据共享

组件之间如何数据共享(组件通信)

  • 父 -> 子:props
  • 子 -> 父:自定义event

兄弟之间?其他非父子? :自定义event?
可能的解法

自定义event

var bus = new Vue()// in component A's methodbus.$emit('id-selected', 1)// in component B's created hookbus.$on('id-selected', function(id){  //...})

共享数据源

const srcData = {  count: 0}const vmA = new Vue({  data: srcData})const vmB = new Vue({  data: srcData})

Vuex基本概念

  • state 状态的容器
  • getters 状态的获取函数
  • mutations 修改状态的事件回调函数
  • actions 分发修改状态的事件
const store = new Vuex.Store({  //state  state: {    count: 0  },  //mutations  mutations: {    INIT (state, data) {      state.count = data.count    },    INCREASE (state) {      state.count++    },    DECREASE (state) {      state.count--    }  },  //getters  getters: {    getCount (state) {      return state.count    }  },  //actions  actions: {    init(context){      context.commit('INIT', {        count: 10      })    },    inc(context){      context.commit('INCREASE')    },    dec(context){      context.commit('DECREASE')    }  }})

Vuex基本理解

  • 数据的集合其中处理(DB)
  • 数据的操作集中处理 (CRUD)
  • 所有对数据的操作(CRUD)以请求(commit)的方式提交处理 (DAO)
阅读全文
0 0