vue组件传值有很多,这里只说一下使用props和$emit实现父传子,子传父以及兄弟组件之间传值
1.父传子
//父组件
<template>
<div class="box"> {{ fatherData }}
<son :fatherData="fatherData"></son>//在子组件标签里面传值
</div>
</template>
<script>
import son from './son.vue'
export default {
name: "",
components: {son},
data() {
return {
fatherData: "我是父组件",
};
},
};
</script>
//子组件
<template>
<div class="container">
子组件--{{fatherData}}
</div>
</template>
<script>
export default {
props:["fatherData"],//这里接收父组件传过来的值得时候除数组外还可以利用对象形式,我这里使用数组形式进行接收
name:'',
data(){
return{
}
}
}
</script>
2.子传父(使用$emit)
//父组件
<template>
<div class="box">
{{ fatherData }}
//接收子组件传过来得值是在子组件标签里面 这里使用@deliverySonValue(与子组件$emit内定义的函数
//名字保持一致)接收,@deliverySonValue后面引号内是你在父组件里面需要操作子组件传输过来的数据
//的函数,这里定义为deliverySonValue
<son :fatherData="fatherData" @deliverySonValue="deliverySonValue"></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
name: "",
components: {son},
data() {
return {
fatherData: "我是父组件",
};
},
methods:{
//此处获取子组件传过来的值并且赋值给父组件中原本定义的变量
deliverySonValue(sonValue) {
this.fatherData = sonValue
}
}
};
</script>
//子组件
<template>
<div class="container">
子组件--{{fatherData}} <button @click="btn">点击传值</button>
</div>
</template>
<script>
export default {
props:["fatherData"],
name:'',
data(){
return{
sonValue:'我是子组件得值'
}
},
methods:{
btn() {
//this.$emit('函数名字',要传给父组件的值)
this.$emit('deliverySonValue',this.sonValue)
}
}
}
</script>
3.利用props和$emit实现兄弟组件之间的传值(状态提升)
思路:现有子组件A和B,两个组件共有一个父组件C,A和B为兄弟组件。若想要将A组件内的一个变量传输给B,那么需要先使用$emit将该变量传输给C,由C使用props将变量传输给B,此时就实现了兄弟组件之间的数据传输。下面看代码(图片中使用箭头标注了数据的流向)
分享就到这里,若有不足请谅解指正,欢迎大家一起交流,谢谢~