vue中组件传值方式
父传子:通过v-bind的形式传值,子组件通过props接收。子组件的h2标签中的{{hello}}在页面上的展示为world。
**父组件:**
<div class="home">
<HelloWorld :hello="hello"/>
</div>
data(){
return{
hello: 'world'
}
}
hr
br
**子组件:**
<div class="hello">
<h2>{{ hello }}</h2>
</div>
props: {
hello: String
}
子传父:通过$emit(" 事件 " , " 参数 ")的方式传值
**子组件**
<div class="hello">
<h2 @click="handleClick">{{ hello }}</h2>
</div>
data(){
return{
info: '子组件传值给父组件'
}
},
methods:{
handleClick(){
console.log("123")
this.$emit("handleSon",this.info)
}
}
**父组件**
<div class="home">
<HelloWorld :hello="hello" @handleSon="handleChange" />
</div>
methods:{
handleChange(res){
console.log(res)//在这里可以打印出“子组件传值给父组件”
}
}
非父子组件传值:通过事件总线event bus进行传值。先创建一个bus.js,再main.js中引入。在两个兄弟组件中分别引入bus.js文件。发送方通过bus. e m i t ( " 事 件 名 " , 参 数 ) 发 送 , 接 收 方 在 m o u n t e d 生 命 周 期 钩 子 中 通 过 b u s . emit( " 事件名 " , 参数 )发送,接收方在mounted生命周期钩子中通过bus. emit("事件名",参数)发送,接收方在mounted生命周期钩子中通过bus.emit( “” , (res)=>{ console.log(res) })来接收。
两个兄弟组件
<div class="home">
<HelloWorld :hello="hello" @handleSon="handleChange" />
<HelloHao :hello="hello" />
</div>
**兄弟组件--helloworld --发送方-----------------------------------------------------------**
<h2 @click="eventBus">事件总线</h2>
data(){
return{
info: '子组件传值给父组件',
res: '事件总线'
}
},
methods:{
eventBus(){
bus.$emit("eventWorld",this.res)
}
}
**兄弟组件--hellohao--接收方--------------------------------------------------------------**
mounted(){
bus.$on("eventWorld",res=>{
console.log(res)//在这里打印出“ 事件总线 ”
})
}
另外bus.js代码
import Vue from 'vue'
var bus = new Vue();
export default bus
main.js代码中只需要加一行代码:Vue.prototype.bus = new Vue();即可