通过 Prop 向子组件传递数据
001:父组件=====》子组件通信
<template>
<div>
<h1>这里是父元素</h1>
//******
<childComponent :detailMes="detailMes"/>
</div>
</template>
<script>
import childComponent from './childComponent'
export default {
name:"parentComponent",
data() {
return {
detailMes:'111'
}
},
components: {
childComponent,
},
}
</script>
子组件
<template>
<div>
数据需要从父元素传递过来哦:{{detailMes}}
</div>
</template>
<script>
export default {
name:'childComponent',
data() {
return {
}
},
props:['detailMes'],
methods: {
name() {
}
}
}
002:子组件=====》父组件通信
(要求父组件先给子组件一个函数)
列表数据在父组件,循环的ul>li在子组件,现在在组件删除数据,需要通知父组件
<template>
<div>
<h1>这里是父</h1>
//父组件先给子组件一个函数
<childComponent :list="list" :del="del"/>
</div>
</template>
<script>
import childComponent from './childComponent'
export default {
data() {
return {
list:[
{id:"001",stuName:'学生a'},
{id:"002",stuName:'学生b'},
]
}
},
components: {
childComponent,
},
methods: {
del(id) {
const idx=this.list.findIndex(v=>v.id==id);
if(idx>-1){
this.list.splice(idx,1)
}
// this.list=this.list.filter(item=>item.id!==id)
}
},
}
</script>
<template>
<div>
子组件
<ul>
<li v-for="item of list" :key="item.id">
<span>{{item.stuName}}</span>
<button @click="dele(item.id)" class="red">x</button>
</li>
</ul>
</div>
</template>
<script>
export default {
name:'childComponent',
data() {
return {
}
},
props: {
// 父元素传递过来的方法
list:{},
// 父组件传递过来的方法
del:{}
},
methods: {
dele(ids) {
// 通知父元素,快删除数据了
// 去调用父组件的方法
this.del(ids);
}
}
}
003 传递 多层传递下去
<template>
<div>
<h1>这里是父</h1>
<childComponent :msg="msg"/>
</div>
</template>
<script>
import childComponent from './childComponent'
export default {
data() {
return {
msg:'这条数据需要通过层层传递下去'
}
},
components: {
childComponent,
},
}
</script>
<template>
<div>
子组件
<grandsonComponent :msg="msg"></grandsonComponent>
</div>
</template>
<script>
import grandsonComponent from '@/components/grandsonComponent.vue';
export default {
components: {
grandsonComponent,
},
props: {
msg:{}
},
}
</script>
<template>
<div>
这是统计的{{msg}}的数据
</div>
</template>
<script>
export default {
name:'grandsonComponent',
props: {
msg: {}
},
//props:['msg']
}
</script>