Vue组件通信
Vue父子组件通信
1.父组件向子组件传值
父组件通过在子组件的组件标签添加属性把值传递给子组件,子组件在props里声明接收
父组件:
<template>
<div class="father">
<com-son :sons="sonList"></com-son>
</div>
</template>
<script>
import comSon from './son'
export default {
name: 'HelloWorld',
components: { comSon },
data() {
return {
sonList: ['小白', '小红', '小蓝','小绿']
}
}
}
</script>
子组件声明接收并运用传过来的值
<template>
<div>
<span v-for="(item, index) in sons" :key="index">{{item}}</span>
</div>
</template>
<script>
export default {
props: ['sons']
}
</script>
2.子组件向父组件传值
子组件通过$emit(方法名,值)发送事件,父组件通过v-on(@)来监听事件
子组件:
<template>
<div>
<span v-for="(item, index) in sons" :key="index" @click="emitIndex(index)">{{item}}</span>
</div>
</template>
<script>
export default {
props: ['sons'],
methods: {
emitIndex(index){
this.$emit('onEmitIndex',index)
}
}
}
</script>
父组件:
<template>
<div class="father">
<com-son :sons="sonList" @onEmitIndex="onEmitIndex"></com-son>
<p>{{currentIndex}}</p>
</div>
</template>
<script>
import comSon from './son'
export default {
name: 'HelloWorld',
components: { comSon },
data() {
return {
currentIndex: -1,
sonList: ['小白', '小红', '小蓝','小绿']
}
},
methods:{
onEmitIndex(idx){
this.currentIndex = idx
}
}
}
</script>
中央事件总线
这种方法是通过创建一个新的Vue实例
var Event = new Vue();//定义一个空的Vue实例
让这个空的Vue实例Event完成事件的发送和监听,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级。
假如两个组件A、B实现A 组件向B组件传值在A组件:
<button @click="send">将数组发送给C组件</button>
var Event = new Vue();//定义一个空的Vue实例
methods: {
send() {
Event.$emit('data-a', this.name);
}
}
B组件同样通过这个Event来监听事件data-a:
mounted() {//在模板编译完成后执行
Event.$on('data-a',name => {
this.name = name;//箭头函数内部不会产生新的this,这边如果不用=>,this指代Event
})
Vue状态管理
不细说。。。
React组件通信
React父子组件通信
1.父组件向子组件传值
父组件在子组件的组件标签上传值,子组件在this.props上取到
父组件:
<Timer order={order} /> //倒计时组件
子组件:
let order = this.props.order;//订单详情
2.子组件向父组件传值
子组件更新组件状态,通过回调函数的方式传递给父组件。子组件调用父组件通过props传给它的函数更新父组件state,进而完成子组件向父组件的通讯。父组件要更新状态必须调用this.setState()
所以根本上是通过操作父组件里的方法更新状态,父组件把更新状态的方法作为props传给子组件,子组件在合适的时机调用,并把值带过来
父组件:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//导入子组件
import Child from './child.js';
class App extends Component {
constructor(props){
super(props);
this.state = {
msg: '父组件初始msg'
}
}
//父组件回调函数,更新state,进而更新父组件。
callback=(msg)=>{
// setState方法,修改msg参数,值是由子组件传过来。
this.setState({msg});
}
render() {
return (
<div className="App">
<p>子组件传值实验: {this.state.msg}</p>
<Child callback={this.callback} ></Child>
</div>
);
}
}
export default App;
子组件:
import React from "react";
class Child extends React.Component{
constructor(props){
super(props);
this.state={
msg: '子组件msg传值'
}
}
//通过props调用回调函数传值
trans=()=>{
this.props.callback(this.state.msg);
}
render(){
return(
<div>
<button onClick={this.trans}>激发trans事件,传值给父组件</button>
</div>
)
}
}
export default Child;
消息订阅与发布
借助一些库pub-sub、event等