Blogger Information
Blog 70
fans 1
comment 0
visits 53108
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示父子组件之间通信方式
葡萄枝子
Original
646 people have browsed it

实例演示父子组件之间通信方式

作业内容:实例演示父子组件之间通信方式

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <!-- 引入vue框架库 -->
  8. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  9. </head>
  10. <body>
  11. <div class="app">
  12. <!-- 父组件 -->
  13. <p>{{like}} <button @click="addNum">{{num}} +</button></p>
  14. <!-- 子组件1 -->
  15. <!-- 父组件向子组件传参通过自定义属性 -->
  16. <child-component1 :like-type="like" :like-num="num"></child-component1>
  17. <!-- 子组件2 -->
  18. <!-- 子组件向父组件传参通过自定义方法 -->
  19. <child-component2 :like-type="like" :like-num="num" @like-change="likeMethod"></child-component2>
  20. </div>
  21. <script>
  22. const vm = new Vue({
  23. el: '.app',
  24. data() {
  25. return {
  26. like: '喜欢',
  27. num: 0,
  28. }
  29. },
  30. // 局部组件
  31. components: {
  32. // 组件1,父组件向子组件传参
  33. childComponent1 : {
  34. // props 接受父组件向子组件的自定义传参
  35. props: ['likeType', 'likeNum'],
  36. // 组件模板显示父组件的传参
  37. template: `<p>like-type: {{likeType}}, like-num: {{likeNum}}</p>`,
  38. },
  39. // 组件2,子组件向父组件传参
  40. childComponent2 : {
  41. // props 接受父组件向子组件的自定义传参
  42. props: ['likeType', 'likeNum'],
  43. // 改变父组件的喜欢类型和喜欢数量
  44. template: `<p>
  45. <label for="like-type">like-type</label> <input text="text" id="like-type" value="" /><br />
  46. <label for="like-num">like-num</label> <input text="text" id="like-num" value="" /><br />
  47. <button @click="$emit('like-change', $event)">change</button>
  48. </p>`
  49. ,
  50. },
  51. },
  52. // 方法
  53. methods: {
  54. // 父组件 num 自增
  55. addNum() {
  56. this.num++;
  57. },
  58. // 子组件改变父组件 like-type 和 like-num
  59. likeMethod(ev) {
  60. let likeType = ev.target.parentNode.querySelector('#like-type').value;
  61. let likeNum = ev.target.parentNode.querySelector('#like-num').value;
  62. this.like = likeType;
  63. this.num = likeNum;
  64. },
  65. },
  66. });
  67. </script>
  68. </body>
  69. </html>

1. 父组件向子组件通过自定义属性传参

  • 点击喜欢后面的自增按钮3次,父组件喜欢数为 3+,父组件向子组件1传参显示图

父组件向子组件传参

2. 子组件向父组件通过自定义方法传参

  • 在上图中,修改 like-type 为 点赞 ,like-num 为 100 点击 change 子组件2,改变父组件的原来喜欢字符和喜欢数显示图

子组件向父组件传参

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments