第一种:父组件向子组件传递一个函数,子组件通过调用函数向父组件返回值
父组件:
<template>
<h1>姓名:{{name}}</h1>
<h1>年龄:{{age}}</h1>
<HelloWorld :getName="getName"></HelloWorld>
</template>
<script>
import HelloWorld from "@/components/HelloWorld";
export default {
name: "parent_one",
components:{
HelloWorld,
},
data(){
return{
name:'',
age:0,
}
},
methods:{
getName(name){
console.log("接收到参数:"+name);
if(name==null)
return;
this.name=name;
},
getAge(age){
console.log("接收到参数:"+age);
}
}
}
</script>
<style scoped>
</style>
子组件:
<template>
<h1>我是菜鸡</h1>
<button v-on:click="sendName">点我传递参数</button>
</template>
<script>
export default {
name:"HelloWord",
data(){
return{
name:'张三',
age:23
}
},
props:['getName'],
methods:{
sendName(){
this.getName(this.name);
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
App.vue
<template>
<div>
<parent-one></parent-one>
</div>
</template>
<script>
import ParentOne from './components/parent_one'
export default {
name:'App',
components:{
ParentOne
}
}
</script>
第二种:通过自定义事件实现子组件向父组件传值$emit
children-one.vue
<template>
<div id="childrenOne">
<h1>学生姓名{{username}}</h1>
<button v-on:click="sendName">点我传递李四</button>
</div>
</template>
<script>
export default {
name: "childern-one",
data(){
return {
username:'李四'
}
},
methods:{
sendName(){
this.$emit('jojo',this.username)
}
}
}
</script>
<style scoped>
</style>
parent-one.vue
<template>
<h1>姓名:{{name}}</h1>
<h1>年龄:{{age}}</h1>
<HelloWorld ref="abcd"></HelloWorld>
<children-one v-on:jojo="getName"></children-one>
</template>
<script>
import HelloWorld from "@/components/HelloWorld";
import ChildrenOne from "./childern-one"
export default {
name: "parent_one",
components:{
HelloWorld,
ChildrenOne
},
data(){
return{
name:'',
age:0,
}
},
methods:{
getName(name){
console.log("接收到参数:"+name);
if(name==null)
return;
this.name=name;
},
getAge(age){
console.log("接收到参数:"+age);
}
},
}
</script>
<style scoped>
</style>
第三种:通过ref可以直接操作子组件的方法
parent-one.vue
<template>
<h1>姓名:{{name}}</h1>
<h1>年龄:{{age}}</h1>
<HelloWorld ref="abcd"></HelloWorld>
<children-one v-on:jojo="getName"></children-one>
<button v-on:click="parentMethod"></button>
<children-two ref="c1"></children-two>
</template>
<script>
import HelloWorld from "@/components/HelloWorld";
import ChildrenOne from "./childern-one"
import ChildrenTwo from "./children-two"
export default {
name: "parent_one",
components:{
HelloWorld,
ChildrenOne,
ChildrenTwo
},
data(){
return{
name:'',
age:0,
}
},
methods:{
getName(name){
console.log("接收到参数:"+name);
if(name==null)
return;
this.name=name;
},
getAge(age){
console.log("接收到参数:"+age);
},
parentMethod(){
console.log('sfsdf',this.$refs.c1.username)
this.$refs.c1.childrenMethods();
}
},
}
</script>
<style scoped>
</style>
chiledren-two.vue
<template>
<div>
</div>
</template>
<script>
export default {
name: "children-two",
data(){
return{
username:'王五',
password:'123456'
}
},
methods:{
childrenMethods(){
return this.username
}
}
}
</script>
<style scoped>
</style>