1:vue 父组件向子组件传值——props方法
重点:
父: <app-son :dataList="appData"></app-son>
子: props: { dataList: {type: [Object] } }
//父组件 App.vue
<template>
<div id="app">
<app-son :dataList="appData"></app-son> --第三步:引dataList
</div>
</template>
<script>
import appSon from "./components/appSon/index"; --第一步:导入子组件appSon
export default {
name: 'app',
components: { --第二步:申明子组件appSon
appSon
},
data(){
return {
appData:{
title:"我是父组件的dataList数据"
}
}
}
}
</script>
// 子组件 appSon
<template>
<div>
<p class="red">{{dataList.title}}</p>
</div>
</template>
<script>
export default {
name: 'appSon',
props: { 核心:通过props拿到dataList中的appData
dataList: {
type: [Object],
},
}
}
</script>
2:父组件调用子组件方法——$refs
重点:
父: <p @click='say'>父组件调用子组件方法</p>
<app-son ref="text"></app-son>
this.$refs.text.sayHello('说你好'); //say方法中的
子: sayHello(data){ alert(data); } //由html中的ref,和js中的$refs控制。
//父组件 App.vue
<template>
<div id="app">
<p @click='say'>父组件调用子组件方法</p>
<app-son :dataList="appData" ref="text"></app-son>
</div>
</template>
<script>
import appSon from "./components/appSon/index";
export default {
name: 'app',
components: {
appSon
},
data(){
return {
appData:{
title:"我是父组件的dataList数据"
}
}
},
methods:{
say(){
this.$refs.text.sayHello('说你好');
}
}
}
</script>
// 子组件 appSon
<template>
<div>
<p class="red">{{dataList.title}}</p>
</div>
</template>
<script>
export default {
name: 'appSon',
props: {},
methods:{
sayHello(data){
alert(data);
}
}
}
</script>
3.子组件调用父组件方法并且传参——$emit
子: this.$emit('notice',{name:'回来吃饭',data:'买饮料'}); //子组件被点击时调用,
父: <app-son @notice='handle'></app-son> //父组件得到notice后,触发handle()事件。
//父组件 App.vue
<template>
<div id="app">
<app-son @notice='handle'></app-son>
</div>
</template>
<script>
import appSon from "./components/appSon/index";
export default {
name: 'app',
components: {
appSon
},
data(){
return {
appData:{
title:"我是父组件的dataList数据"
}
}
},
methods:{
handle(){
alert('开始做事');
}
}
}
</script>
// 子组件 appSon
<template>
<div>
<button @click='noticeFather'>点击通知父组件</button>
</div>
</template>
<script>
export default {
name: 'appSon',
props: {},
noticeFather(){
this.$emit('notice',{name:'回来吃饭',data:'买饮料'});
}
}
</script>