Vue数据传递问题

Vue数据传递

2.0中官方文档,API文档-组件

数据父-子

数据

prop:使用prop传递数据,单向数据流,.sync 双向绑定[语法糖:foo="" @update:foo="val => bar = val"].
v-model::value="something" v-on:input="something = arguments[0]"
v-bind

v-bind="$props" 会把object props中的数据绑定都绑定

$props:对象,代表当前组件收到的 props。Vue 示例代理访问到这个 props 对象的属性们

1
2
3
4
<child v-bind="$props"></child>
<child :showHit="showHit" :message="message"></child>

1
2
3
4
5
6
{
props: {
showHit: Boolean,
message: Boolean
},
}

v-bind='Object': 相当于v-bind:ObjectKey="value" ...

v-bind='value': String

事件

发送事件
1
this.$emit('eventName'arguments)
接受事件
1
this.$on('eventName'function(){})

子-父数据传递

子-父只能用事件传递,注意父级接收事件只能用v-on

1
<child v-on:eventName="event"></child>

非父子数据传递

使用eventBus事件传递数据

1
2
3
4
5
6
7
var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 接收组件 A 中的事件
bus.$on('id-selected', function(id){})

dispatch

直接查找到父级进行通信

摘自element-ui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
}

broadcast

广播

摘自element-ui

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function broadcast(componentName, eventName, params) {
this.$children.forEach(child => {
var name = child.$options.componentName;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
broadcast(componentName, eventName, params) {
broadcast.call(this, componentName, eventName, params);
}