vue父组件调用子组件方法、父组件向子组件传值、子组件向父组件传值
一、父组件调用子组件方法
父组件代码 parent.vue
<template>
<div>
<button @click="parentFun">{
{msg}}</button>
<child ref="child"></child>
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
data () {
return {
msg: '我是父组件按钮'
}
},
components: {
child,
},
methods:{
parentFun(){
this.$refs.child.childFun();
}
}
}
</script>
<style scoped>
</style>
子组件代码 child.vue
<template>
<div>
我是子组件
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: ''
}
},
methods:{
childFun(){
console.log('我是子组件方法')
},
}
}
</script>
<style scoped>
</style>
点击“我是父组件按钮” 会调用子组件 childFun() 方法
二、父组件向子组件传参
父组件代码 parent.vue
``
<template> <div> <child ref="child" :msg="msg"></child> </div> </template> <script> import child from './child' export default { name: 'parent', data () { return { msg: '我是父组件按钮参数' } }, components: { child, }, methods:{ } } </script> <style scoped> </style>
子组件代码 child.vue
<template>
<div>
我是子组件
</div>
</template>
<script>
export default {
name: 'child',
props:{
msg:String
},
data () {
return {
}
},
methods:{
},
created(){
console.log(this.msg)
}
}
</script>
<style scoped>
</style>
把父组件要传的参数绑定到子组件的标签上,父组件用 props 接收参数,并注明参数类型,这样子组件就会获取到了
三、子组件向父组件传值
父组件代码 parent.vue
``
<template> <div> { {msg}} <child @parentFun="getChildData" ></child> </div> </template> <script> import child from './child' export default { name: 'parent', data () { return { msg: '' } }, components: { child, }, methods:{ getChildData(data){ this.msg = data; } } } </script> <style scoped> </style>
子组件代码 child.vue
<template>
<div>
<button @click="sendParentMsg">我是子组件按钮</button>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: '我是子组件的参数'
}
},
methods:{
sendParentMsg(){
//parentFun: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
this.$emit('parentFun',this.msg)
},
}
}
</script>
<style scoped>
</style>
好了,常用的几种父子组件之间的参数传递方法我整理了一些,希望对大家有所帮助
转载于//www.cnblogs.com/shizk/p/11498134.html
还没有评论,来说两句吧...