示例一:父组件向子组件传值
- 父组件:
父组件
// 引入子组件
import HChild from './Child'
export default {
name: 'Parent',
components: {
HChild
},
data () {
return {
msg: 'data from parent'
}
},
methods: {
fun () {
console.log('parent fun')
}
}
}
- 子组件:
子组件
调用父组件的数据和方法
export default {
name: 'Child',
methods: {
showParent () {
// 获取到所有的子组件
console.log(this.$parent)
// 获取指定子组件中的指定数据
console.log(this.$parent.msg)
// 调用子组件的方法
this.$parent.fun()
}
}
}
注意:在钩子方法mounted中无法获取到父组件中的数据和方法
结果:
- 子组件:
子组件
export default {
name: 'Child',
data () {
return {
msg: 'msg from child'
}
},
methods: {
fun () {
console.log('child fun')
}
}
}
- 父组件:
父组件
// 引入子组件
import HChild from './Child'
export default {
name: 'Parent',
components: {
HChild
},
mounted () {
// 获取到所有的子组件,结果是一个数组
console.log(this.$children)
// 获取指定子组件中的指定数据
console.log(this.$children[0].msg)
// 调用子组件的方法
this.$children[0].fun()
}
}