VueX

2019-01-03  本文已影响0人  AMONTOP

1、state ——》储存初始化数据
2、getters ——》对State 里面的数据二次处理(对数据进行过滤类似filter的作用)比如State返回的为一个对象,我们想取对象中一个键的值用这个方法
3、mutations ——》对数据进行计算的方法全部写在里面(类似computed) 在页面中触发时使用
this.$store.commit('mutationName')触发Mutations方法改变state的值
4、actions ——》 处理Mutations中已经写好的方法 其直接触发方式是 this.$store.dispatch(actionName)
5、modules ——》模块化Vuex

1、示例一: 利用store共享数据,使得子父组件使用同一个数据

src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)  //必须有这一行,否则报错

// 创建一个store实例
export default new Vuex.Store({
  state: {
    order: {
      'counter': 1,
      'downmenu': 1,
      'radios': 1
    }, // 存放订单信息
    totalPrice: 0
  },
  getters: {       //就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
    getOrder (state) {
      return state.order ? state.order : {}
    },
    getTotalPrice (state) {
      return state.totalPrice > 0 ? `¥ ${state.totalPrice}` : 0
    }
  },
  mutations: {    //更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
    updateOrder (state, data) { // data = {key: value}
      // console.log(data)
      state.order[data[0]] = data[1]
    },
    updatePrice (state, price) {
      state.totalPrice = price
    }
    // increment (state) {
    //   state.count++
    // },
    // decrease (state) {
    //   state.count--
    // }
  },
  actions: {        //actions不是必须的,但是在运用到异步时就要用到actions例如setTimeOut
    updateOrder (context, data) {
      context.commit('updateOrder', data)
    },
    updatePrice (context, price) {
      context.commit('updatePrice', price)
    }
  }
})

src/components/slots/child.vue

<template>
    <div class="child">子组件
        <slot name="s1"></slot>
        <hr/>
        <slot name="s2" text="传递的数据"></slot>
        <slot>no things!</slot>
        <div><button @click="min" class="btn btn-warning">递减</button>仓库中store: {{getCount}}</div>
    </div>
</template>
<script>
export default {
  name: 'child',
  computed: {
    getCount () {
      return this.$store.getters.getState
    }
  },
  methods: {
    min () {
      this.$store.dispatch('decrease')
    }
  }
}
</script>
<style scoped>
p {
    font-size: 16px;
}
</style>

src/components/slots/Outter.vue

<template>
    <div>
        outter<br/>
        store状态管理:{{getCount}}
        <button class="btn" @click="add">叠加</button>
    </div>
</template>
<script>
export default {
  name: 'outter',
  data () {
    return {
    }
  },
  computed: {
    getCount () {
      return this.$store.getters.getState
    }
  },
  methods: {
    add () {
      this.$store.dispatch('increment')
    }
  }
}
</script>
<style scoped>
</style>
上一篇 下一篇

猜你喜欢

热点阅读