一.父组件向子组件传值
父组件
<template>
<div class="parent">
<!--在父组件加入子组件的地方 对父组件的数据进行绑定传输到子组件-->
<!-- :自定义名称(子组件在props里面引用)=要传输的数据(对象) -->
<child :param1="msg" :param2="params"/>
</div>
</template>
<script>
import child from './child'
export default {
components: {child},
name: 'parent',
data() {
return {
msg: '我是父组件',
params: {
a: 1,
b: "我是父组件集合"
}
}
}
}
</script>
子组件
<template>
<div class="child">
<p>{{param1}}</p>
<p>{{param2}}</p>
</div>
</template>
<script>
export default {
name: 'child',
props: {
param1: {
type:String, //类型可以定义
default:'' //默认是空值
},
param2: {
type:Object,
default () {
return {
// 可以为空,也可以自己定义
}
}
}
}
}
</script>
二.子组件向父组件传值
在子组件使用方法
this.$emit('自定义的方法名','传父组件的值')
,父组件使用v-on或者@绑定自定义的方法,然后触发父组件中的方法进行传值
父组件
<template>
<div class="parent">
<child @toParam1="parent1" @toParam2="parent2" />
<p>{{msg}}</p>
<p>{{params}}</p>
</div>
</template>
<script>
import child from './child'
export default {
components: {child},
name: 'parent',
data() {
return {
msg: '我是父组件',
params: {
a: 1,
b: "我是父组件集合"
}
}
},
methods: {
parent1 (param) {
this.msg = param
},
parent2 (param) {
this.params = param
}
}
}
</script>
子组件
<template>
<div class="child">
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: '我是子组件',
params: {
a: 1,
b: "我是子组件集合"
}
}
},
created() {
this.toParam()
},
methods: {
toParam () {
// 自定事件 $emit ==>this.$emit('自定义的方法,在父组件引用子组件的地方用','要传给父组件的值')
this.$emit('toParam1',this.msg)
this.$emit('toParam2',this.params)
}
}
}
</script>
三.父组件调用子组件的方法
父组件
<template>
<div class="parent">
<child ref="child"/>
<button @click="pl">父组件按钮</button>
</div>
</template>
<script>
import child from './child'
export default {
components: {child},
name: 'parent',
data() {
return {
msg: '我是父组件',
params: {
a: 1,
b: "我是父组件集合"
}
}
},
methods: {
pl () {
this.$refs.child.cl()
}
}
}
</script>
子组件
<template>
<div class="child">
</div>
</template>
<script>
export default {
name: 'child',
methods: {
cl () {
console.log("我是子组件的方法")
}
}
}
</script>