vuex Actions案例演示

2018-05-18 18:10:00
admin
原创
321
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vuex 测试实例</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/2.3.0/vuex.min.js"></script>
</head>
<body>
<div id="app">

</div>

<script>
// make sure to call Vue.use(Vuex) if using a module system

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
  	increment: state => state.count++,
    decrement: state => state.count--,
	incrementPayload: (state,payload) => state.count += payload.amount,
	incrementObject: (state,payload) => state.count += payload.amount
  },
  actions: {
    increment (context) {
      context.commit('increment')
    },
	//context参数解构,解构成员commit
	incrementDestructuring ({commit}) {
      commit('increment')
    },
	incrementAsync ({ commit }) {
     setTimeout(() => {
      commit('increment')
     }, 1000)
    },
	//以载荷形式分发
	incrementPayload ({commit},payload) {
      commit('incrementPayload',payload)
    },
	//以对象形式分发
	incrementObject ({commit},payload) {
      commit('incrementObject',payload)
    }
  }
})


// 创建一个 Counter 组件
const Counter = {
  template: `<div>
  <p>{{ count }}</p>
  <p>
    <button @click="incrementMutation">+ Mutation</button>
    <button @click="decrement">-</button>
    <button @click="incrementAction">+ Action</button>
    <button @click="incrementActionDestructuring">+ Action by Destructuring</button>
    <button @click="incrementAsync">+ Action Async</button>
    <button @click="incrementPayload">+ Action Payload</button>
    <button @click="incrementObject">+ Action Object</button>
  </p>
</div>`,
  computed: {
    count () {
		return this.$store.state.count
    }
  },
  methods: {
    incrementMutation () {
      this.$store.commit('increment')
    },
    decrement () {
    	this.$store.commit('decrement')
    },
	incrementAction () {
      this.$store.dispatch('increment')
    },
	incrementActionDestructuring () {
      this.$store.dispatch('incrementDestructuring')
    },
	incrementAsync () {
      this.$store.dispatch('incrementAsync')
    },
	incrementPayload () {
      // 以载荷形式分发
      this.$store.dispatch('incrementPayload', {
        amount: 10
      })
    },
	incrementObject () {
      // 以对象形式分发
      this.$store.dispatch({
        type: 'incrementObject',
        amount: 10
      })
    }
	  
  }
}

const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
</script>
</body>
</html>				
								
								
				
文章分类
联系我们
电话: 18902328227
Email: 2689701946@qq.com
QQ: 2689701946
微信: 18902328227
地址: 广州番禺区繁华路
  • 在线客服
  • 关注微信
  • 联系电话
    • 欢迎咨询
    • 欢迎加入QQ群 303257430
  • 公众号:源宝网络
    • 联系电话及微信号 18902328227