本文转自:https://blog.51cto.com/u_14900374/2550173

简介
vue中组件与组件的关系存在两类:父子组件与非父子组件。
如下图所示,三个组件中就包含了父子组件与非父子组件两种情况,这里组件之间的交互主要由值传递和事件触发调用两种方式,这里先分享下父组件向子组件值传递。
方式
父组件可以向子组件传递的值有三种类型
1、属性变量或者纯文本
2、函数名
3、父组件自身实例(this)
例子
假设有两个组件App.vue和Sub1.vue,其中App.vue为父组件,Sub1.vue为子组件。
父组件App.vue
<template>
<!--父组件传递titile,run,home给子组件sub1-->
<!--其中title为属性,run为方法,this为父组件实例的指针-->
<sub1 :title="title" :run="run" :home="this" ref="deleteConfirm"/>
</template>
<script>
//导入子组件
import Sub1 from './Sub1.vue'
export default {
name: 'app',
data() {
return {
title : 'test'
}
},
methods {
run() {
console.log('parent')
}
},
components: {
Sub1 //挂载子组件Sub1
}
}
</script>
子组件Sub1.vue
<template>
<!--子组件接收父组件传过来的title-->
<module :title="title" : ref="deleteConfirm"/>
<!--这里点击button可以调用父组件的run方法-->
<button :click="run()"></button>
<!--runParent内部通过父组件的this指针调用父组件的属性和方法-->
<button :click="runParent()"></button>
</template>
<script>
export default {
name: "Sub1",
data() {
return {
title: ''
}
},
//1.第一种方法,用数组的方式接收父组件的传值:title,run,home
props: ['title','run','home'],
,methods {
runParent() {
//可以通过父组件实例this.home直接调用父组件中的方法。
console.log(this.home.title);
this.home.run();
}
}
}
</script>
prop接收参数
prop有两种接收父组件传递的参数语法。
第一种就是上面的props: [‘title’,‘run’,‘home’],这种数组方式
第二种:我们也可以在传递值的时候对prop进行校验。
常见的类型:
String
Number
Boolean
Array
Object
Date
Function
Symbol
上面的Props可以改成如下:
props: {
title: { //接收父组件传递过来的title
type: String,
default() {
//如果父组件没有传递title变量,则使用default()获取一个默认值
return this.$t('commons.title')
}
},
run: { //接收父组件传递过来的run方法,
type: Function,
default: function () {
console.log('hello')
}
},
home: { //接收父组件本身
type: Object,
}
},
1631

被折叠的 条评论
为什么被折叠?



