派发器初识,Vue中抽离派发器方法
- vue特性
- 组件化框架 -> es6模块化
- 数据双向绑定
- 派发器思想
- type => 事件 => 逻辑 => type => 派发器 => 数据的更改
actions 定义不同的type
reducers 事件逻辑
dispatchers 先拿到组件实例数据,去reducer各个方法中处理,然后根据type获取对应结果
<!-- src/components/Counter/Index.vue -->
<template>
<div>
<CounterResult :result='result' />
<div>
<CounterButton innerText='-' action='PLUS' @dispatch='dispatch' />
<CounterButton innerText='+' action='MINUS' @dispatch='dispatch' />
</div>
</div>
</template>
<script>
import CounterResult from './Result';
import CounterButton from './Button';
import dispatch from '@/dispatchers/counter';
export default {
name: 'Counter',
components: {
CounterResult,
CounterButton
},
data () {
return {
result: 0
}
},
methods: {
dispatch (...args) {
// this传入外层函数,然后args散播进返回的内层函数
dispatch(this)(...args);
}
}
}
</script>
<!-- src/components/Counter/Result.vue -->
<template>
<h1>{{result}}</h1>
</template>
<script>
export default {
name: 'CounterResult',
props: {
result: Number
}
}
</script>
<!-- src/components/Counter/Button.vue -->
<template>
<button :action='action' @click="compute">
{{innerText}}
</button>
</template>
<script>
export default {
name: 'CounterButton',
props: {
innerText: String,
action: String
},
methods: {
compute () {
this.$emit('dispatch', this.action);
}
}
}
</script>
// src/actions/counter.js
const PLUS = 'PLUS';
const MINUS = 'MINUS';
export {
PLUS,
MINUS
}
// src/reducers/counter.js
function counterReducer(data) {
function plus () {
return data.result - 1;
}
function minus () {
return data.result + 1;
}
return {
plus,
minus
}
}
export default counterReducer;
// src/dispatchers/counter.js
import reducer from '@/reducers/counter';
import { PLUS, MINUS } from '@/actions/counter';
export default (ctx) => {
console.log(ctx);
const {
plus,
minus
} = reducer(ctx.$data);
return function (type, ...args) {
switch (type) {
case PLUS:
ctx.result = plus(...args);
break;
case MINUS:
ctx.result = minus(...args);
break;
default:
break;
}
}
}