vue2.x父子组件传值方式
1.父传子:
1.1 父组件设置传递属性
<!-- 搜索组件 -->
<Search
:searchInfo="searchInfo" //父组件要传给子组件的值 "searchInfo"
>
</Search>
1.2 子组件通过props接收
<template>
<div>
//子组件通过props接收的是值,可以在子组件的模板中直接使用
<div v-for="i in searchInfo" :key=i.id>
<span>
{{i.name}}
</span>
</div>
</div>
</template>
<script>
export default {
props: ["searchInfo"], //通过[]可以接收任意类型
// 子组件通过props接收的是值,可以在子组件的钩子函数中直接用this使用
created(){
console.log(this.searchInfo)
}
}
</script>
2.子传父
2.1 子组件通过this.$emit的方式传递给父组件
<template>
<div>
<button @click=handle(index,rows)>传递给父组件</button>
</div>
</template>
<script>
export default {
methods:{
handle(index,rows){
//通过this.$emit将operation已事件的方式传递给父组件,并将index,rows作为参数传递
this.$emit("operation", index,rows);
}
}
}
</script>
2.2 父组件在标签上通过@xxx="xxx"接收
<template>
<div>
<!-- 搜索组件 -->
//searchInfo为传递给子组件的属性
//operation为子组件传递给父组件的属性
<Search :searchInfo="searchInfo" @operation="operation"></Search>
</div>
</template>
<script>
export default {
methods:{
//子组件传递的事件在标签上接收之后可以在methods中直接调用
//并可以拿到子组件的传递的参数index和rows
operation(index, rows) {
console.log(index,rows)
}
}
}
</script>