1.父组件向子组件传递数据
子组件通过props
属性接收父组件传递的数据。
父组件:
<template>
<div>
<!-- 引用的子组件, :msg动态绑定message -->
<Son :msg="message" :user="userInfo"></Son>
</div>
</template>
<script>
export default{
data() {
return {
message: 'hello vue.js',
userinfo: { name:'zs', age: 20 }
}
}
}
</script>
子组件:
<template>
<div>
<h5>Son 组件</h5>
<p>父组件传递过来的 msg 值是: {{ msg }}</p>
<p>父组件传递过来的 user 值是: {{ user }}</p>
</div>
</template>
<script>
<!-- 获取父组件传递的值 -->
<!-- 1.第一种方法,props写成数组形式 -->
props: ['msg','user']
<!-- 2.第二种方法,props写成对象形式 -->
props: {
msg: {
type: String, // 类型
default: '' // 默认值
}
}
</script>
2.子组件向父组件传递数据
通过自定义事件$emit
子组件:
<template>
<div>
<button @click="init()">click</button>
</div>
</template>
<script>
export default {
data() {
return {
message: '我中意内啊!'
}
},
method: {
init() {
// 通过 $emit() 触发自定义事件
this.$emit('msg',this.message)
}
}
}
</script>
父组件:
<template>
<div>
<Son @msg="getMessage"></Son>
</div>
</template>
<script>
export default {
data() {
return {
msgFromSon: ''
}
},
method: {
// val就是子组件传递的数据
getMessage(val) {
this.msgFromSon = val
console.log(val)
}
}
}
</script>
3.父组件调用子组件的方法
通过$refs
来调用,步骤如下
- 在父组件引用的子组件中声明
ref
- 通过vue实例自带的
$refs
调用
父组件:
<template>
<div>
<!-- 定义ref -->
<Son ref="sonRef"></Son>
<button @click="init()">click</button>
</div>
</template>
<script>
export default{
methods: {
init() {
// 调用子类方法
this.$refs.sonRef.getMessage()
}
}
}
</script>
子组件:
<script>
export default {
method: {
getMessage() {
console.log("我中意内啊!")
}
}
}
</script>
4. 子组件调用父组件方法
第一种方法:通过this.$parent.event
来调用父组件的方法
子组件:
<template>
<div>
<button @click="childMethod()">click</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
// 调用父组件方法
this.$parent.fatherMethodatherMethod();
}
}
};
</script>
父组件:
<template>
<div>
<child></child>
</div>
</template>
<script>
export default {
methods: {
fatherMethod() {
console.log('我中意内啊!');
}
}
};
</script>
第二种方法:在子组件里用$emit
向父组件触发一个事件,父组件@监听该事件
子组件:
<template>
<div>
<button @click="childMethod()">click</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
</script>
父组件:
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
export default {
methods: {
fatherMethod() {
console.log('我中意内啊!');
}
}
};
</script>
第三种方法:父组件把方法传入子组件中,在子组件中调用这个方法
子组件:
<template>
<div>
<button @click="childMethod()">click</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod() {
// 判断fatherMethod是否存在
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
};
</script>
父组件:
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
methods: {
fatherMethod() {
console.log('我中意内啊!');
}
}
};
</script>
前两种用的比较多!!!