vue父组件调用子组件方法、父组件向子组件传值、子组件向父组件传值

﹏ヽ暗。殇╰゛Y 2023-06-01 12:38 91阅读 0赞

一、父组件调用子组件方法

父组件代码 parent.vue

  1. <template>
  2. <div>
  3. <button @click="parentFun">{
  4. {msg}}</button>
  5. <child ref="child"></child>
  6. </div>
  7. </template>
  8. <script>
  9. import child from './child'
  10. export default {
  11. name: 'parent',
  12. data () {
  13. return {
  14. msg: '我是父组件按钮'
  15. }
  16. },
  17. components: {
  18. child,
  19. },
  20. methods:{
  21. parentFun(){
  22. this.$refs.child.childFun();
  23. }
  24. }
  25. }
  26. </script>
  27. <style scoped>
  28. </style>

子组件代码 child.vue

  1. <template>
  2. <div>
  3. 我是子组件
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'child',
  9. data () {
  10. return {
  11. msg: ''
  12. }
  13. },
  14. methods:{
  15. childFun(){
  16. console.log('我是子组件方法')
  17. },
  18. }
  19. }
  20. </script>
  21. <style scoped>
  22. </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

  1. <template>
  2. <div>
  3. 我是子组件
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'child',
  9. props:{
  10. msg:String
  11. },
  12. data () {
  13. return {
  14. }
  15. },
  16. methods:{
  17. },
  18. created(){
  19. console.log(this.msg)
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </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

  1. <template>
  2. <div>
  3. <button @click="sendParentMsg">我是子组件按钮</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name: 'child',
  9. data () {
  10. return {
  11. msg: '我是子组件的参数'
  12. }
  13. },
  14. methods:{
  15. sendParentMsg(){
  16. //parentFun: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
  17. this.$emit('parentFun',this.msg)
  18. },
  19. }
  20. }
  21. </script>
  22. <style scoped>
  23. </style>

  

好了,常用的几种父子组件之间的参数传递方法我整理了一些,希望对大家有所帮助

转载于:https://www.cnblogs.com/shizk/p/11498134.html

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读