Blogger Information
Blog 48
fans 3
comment 1
visits 30371
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Vue 组件之间的通信
吴长清
Original
413 people have browsed it

vue组件之间的通信

父组件App.vue

  1. <template>
  2. <fieldset>
  3. <legend>组件间通信</legend>
  4. <!-- 使用父组件 Children.vue -->
  5. <!-- 向子组件传值num 并接收Children.vue文件传来的值-->
  6. <Children :num="num" @app_edit="app_edit"></Children>
  7. 这是子组件Children.vue传给父组件App.vue的值: {{ num }}
  8. </fieldset>
  9. </template>
  10. <script>
  11. // 引入父组件 Parent.vue
  12. import Children from "./components/Children";
  13. export default {
  14. // 引入组件后 要在此注册
  15. components: {
  16. Children,
  17. },
  18. data() {
  19. return {
  20. num: 0,
  21. };
  22. },
  23. methods: {
  24. app_edit(e) {
  25. console.log("我是父文件的app_edit方法");
  26. // console.log(e);
  27. this.num = e;
  28. },
  29. },
  30. };
  31. </script>

子组件Parent.vue

  1. <template>
  2. <div class="">
  3. <h1>{{ msg }}</h1>
  4. 接受App.vue文件传过来的值为: {{num}} <hr>
  5. <button @click="add_num"> 每次+1</button>
  6. <button @click="cut_num"> 每次-1</button>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. data() {
  12. return {
  13. msg: "这是子组件",
  14. };
  15. },
  16. props:['num'],
  17. methods: {
  18. add_num(){
  19. // console.log(this.num);
  20. console.log("Parent.vue文件下的add_num方法");
  21. // 将传过来的值+1处理传回App.vue
  22. this.$emit('app_edit',this.num+1);
  23. },
  24. cut_num(){
  25. // console.log(this.num);
  26. console.log("Parent.vue文件下的cut_num方法");
  27. // 将传过来的值+1处理传回App.vue
  28. this.$emit('app_edit',this.num-1);
  29. }
  30. },
  31. };
  32. </script>

最终效果

更多组件通信及生命周期参考:http://www.ouyangke.com/front/vue3/3Vue3%E7%BB%84%E4%BB%B6.html

Correcting teacher:PHPzPHPz

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