vue 组件传值(父传子、子传父、兄弟传值)
1. vue的父子传值
父组件
<template>
<div>
父组件
<Children :message='msg'/>
</div>
</template>
<script>
import Children from '../components/AboutCom/Childre.vue'
export default {
components:{
Children
},
data(){
return {
msg:"我是父组件的数据"
};
},
};
</script>
子组件
<template>
<div>
子组件
{{message}}
</div>
</template>
<script>
export default {
props:{
message:{
type:String,
default:""
}
},
};
</script>
在父组件中 在子组件标签中自定义属性 message
传递数据
在子组件的props
中声明接收 可以设置数据类型、默认值等等
2. vue的子父传值
vue的子父传值 需要用到$emit
和v-on
,在子组件使用$emit
来触发事件 父组件用v-on
接收事件函数 函数参数为子组件的数据,接收后在父组件将数据赋值到data
中。
<template>
<div>
<p>父组件:{{childMsg}}</p>
<Children @childMsg="childMsgFn"/>
</div>
</template>
<script>
import Children from '../components/AboutCom/Childre.vue'
export default {
components:{
Children
},
data(){
return {
childMsg:""
};
},
methods:{
chhildMsgFn(val){
this.childMsg=val
}
}
};
</script>
<template>
<div>
子组件
<button @click="msgFn">想父组件传值</button>
</div>
</template>
<script>
export default {
methods:{
msgFn(){
this.$emit('childMsg','我是子组件的数据')
}
}
};
</script>
运行后点击按钮将子组件的数据传到父组件中
3. vue的兄弟传值(非父子传值)
在兄弟传值中 我们需要先建立一个公共的bus 用来存取
/bus.js
import Vue from 'vue'
export default new Vue()
我们需要将两个组件放在同一个父级组件中。 同时在兄弟两个组件中分别引入 bus.js
在哥哥组件中使用bus.$emit
来触发事件 $emit
中有两个参数:第一个参数是触发事件的事件名,第二个参数是传递的数据。
这时我们需要在弟弟组件中使用bus.$on
监听事件触发 $on同样也有两个参数:第一个也是事件名,第二个则是一个函数, 函数参数是哥哥组件传递的数据。
<template>
<div>
我是哥哥
<button @click="changeFn">传数据给弟弟</button>
</div>
</template>
<script>
import bus from '../../utils/bus'
export default {
methods:{
changeFn(){
this.$emit('msgFn','我是哥哥')
}
}
};
</script>
<template>
<div>我是弟弟{{ message }}</div>
</template>
<script>
import bus from "../../utils/bus";
export default {
data() {
return {
message: "",
};
},
mounted() {
bus.$on("msgFn", (val) => {
this.message = val;
});
},
};
</script>