Vue $parent、子组件调用父组件方法,父组件调用子组件方法

超、凢脫俗 2022-10-06 01:50 370阅读 0赞

https://blog.csdn.net/zgrkaka/article/details/100528714

假设层级太深:this.$parent.$parent.getShopCart() 多加一个 $parent 一般两个够了

子组件调用父组件方法

  1. 第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法
  2. 父组件
  3. <template>
  4. <div>
  5. <child></child>
  6. </div>
  7. </template>
  8. <script>
  9. import child from '~/components/dam/child';
  10. export default {
  11. components: {
  12. child
  13. },
  14. methods: {
  15. fatherMethod() {
  16. console.log('测试');
  17. }
  18. }
  19. };
  20. </script>
  21. 子组件
  22. <template>
  23. <div>
  24. <button @click="childMethod()">点击</button>
  25. </div>
  26. </template>
  27. <script>
  28. export default {
  29. methods: {
  30. childMethod() {
  31. this.$parent.fatherMethod();
  32. }
  33. }
  34. };
  35. </script>
  36. 第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
  37. 父组件
  38. <template>
  39. <div>
  40. <child @fatherMethod="fatherMethod"></child>
  41. </div>
  42. </template>
  43. <script>
  44. import child from '~/components/dam/child';
  45. export default {
  46. components: {
  47. child
  48. },
  49. methods: {
  50. fatherMethod() {
  51. console.log('测试');
  52. }
  53. }
  54. };
  55. </script>
  56. 子组件
  57. <template>
  58. <div>
  59. <button @click="childMethod()">点击</button>
  60. </div>
  61. </template>
  62. <script>
  63. export default {
  64. methods: {
  65. childMethod() {
  66. this.$emit('fatherMethod');
  67. }
  68. }
  69. };
  70. </script>

父组件调用子组件

https://www.cnblogs.com/yuzhongyu/p/10825824.html

通过ref直接调用子组件的方法

  1. //父组件中
  2. <template>
  3. <div>
  4. <Button @click="handleClick">点击调用子组件方法</Button>
  5. <Child ref="child"/>
  6. </div>
  7. </template>
  8. <script>
  9. import Child from './child';
  10. export default {
  11. methods: {
  12. handleClick() {
  13. this.$refs.child.sing();
  14. },
  15. },
  16. }
  17. </script>
  18. //子组件中
  19. <template>
  20. <div>我是子组件</div>
  21. </template>
  22. <script>
  23. export default {
  24. methods: {
  25. sing() {
  26. console.log('我是子组件的方法');
  27. },
  28. },
  29. };
  30. </script>

发表评论

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

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

相关阅读