Blogger Information
Blog 46
fans 0
comment 0
visits 39607
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
父子组件之间的通信方式
lus菜
Original
780 people have browsed it

组件之间的传参:

  1. 父组件 子组件 传参: 自定义属性
  2. 子组件 父组件 传参: 自定义方法

父组件向子组件传参:

样式代码:

  1. <!-- 导入vue框架 -->
  2. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  3. <body>
  4. <div id="app">
  5. <!-- 父组件是通过自定义属性的方式将参数传到子组件中的 -->
  6. <btn-inc :my-name="username" :my-count="count"></btn->
  7. </div>
  8. <script>
  9. const vm = new Vue({
  10. el: document.querySelector("#app"),
  11. data() {
  12. return {
  13. username:"为你点赞",
  14. count: 0,
  15. };
  16. },
  17. // 局部组件子组件
  18. components: {
  19. btnInc: {
  20. // props接受父组件向子组件的自定义传参
  21. props: ["myName", "myCount"],
  22. // 报错原因,组件之间的数据传递是单向的,不允许在子组件中更新父组件中的数据
  23. template: `
  24. <div>
  25. <button @click="num++">点赞: + {{num}}</button>
  26. <span>{{myName}}</span>
  27. </div>
  28. `,
  29. data() {
  30. return {
  31. num: this.myCount,
  32. };
  33. },
  34. methods: {
  35. inc(n) {
  36. this.num += n;
  37. },
  38. },
  39. },
  40. },
  41. });
  42. </script>
  43. </body>

效果预览:

子组件向父组件传参:

样式代码:

  1. <!-- 导入vue框架 -->
  2. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  3. <body>
  4. <div id="app">
  5. <!-- 子组件中更新父组件的数据是通过事件完成 -->
  6. <btn-inc :my-name="username" :my-count="count" @click-count="handle"></btn-inc>
  7. </div>
  8. <script>
  9. const vm = new Vue({
  10. // 子组件向父组件传参是通过声明同名事件来实现
  11. el: document.querySelector("#app"),
  12. data() {
  13. return {
  14. username: "菜市场买菜",
  15. count: 0,
  16. };
  17. },
  18. // 局部组件子组件
  19. components: {
  20. btnInc: {
  21. //props接受父组件向子组件的自定义传参
  22. props: ["myName", "myCount"],
  23. // 报错原因,组件之间的数据传递是单向的,不允许在子组件中更新父组件中的数据
  24. template: `
  25. <div>
  26. <button @click="$emit('click-count',10)">点赞: + {{myCount}}</button>
  27. <span>{{myName}}</span>
  28. </div>
  29. `,
  30. },
  31. },
  32. // 父组件更新数据的方法
  33. methods: {
  34. handle(value) {
  35. console.log(vm.count);
  36. this.count += value;
  37. this.username = "商业城";
  38. },
  39. },
  40. });
  41. </script>
  42. </body>

效果预览:

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
Author's latest blog post