Blogger Information
Blog 41
fans 0
comment 0
visits 31026
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Vue 父子组件之间通信方式
陈强
Original
653 people have browsed it

组件

组件是可复用的vue实例,从形式上看就是一个自定义html标签
模板里面第一级只能有一个标签,不能并行;

  • 全局组件:全局可见,声明在vue实例外部
  1. //声明
  2. Vue.component("child-component", childComponent{});
  3. const vm = new Vue({})
  • 局部组件:声明在vue实例内部
  1. const vm = new Vue({
  2. el: ".app",
  3. components: {
  4. MyClick: {
  5. template: `<h1>我是局部组件</h1>`,
  6. },
  7. },
  8. });

父子组件之间通信方式

  • 父组件是通过自定义属性的方式将参数传到子组件中的
  1. <div class="app">
  2. //用子组件自定义属性my-age获取父组件age的值
  3. <my-click :my-age="age"></my-click>
  4. </div>
  5. <script>
  6. const vm = new Vue({
  7. el: ".app",
  8. data() {
  9. return {
  10. age: 28,
  11. };
  12. },
  13. //声明子组件
  14. components: {
  15. myClick: {
  16. props: ["myAge"],
  17. template: `<p>我的年龄是{{myAge}}</p>`,
  18. },
  19. },
  20. });
  21. </script>
  • 子组件中更新父组件的数据是通过事件完成
  1. <div class="app">
  2. //用子组件@click-count绑定的事件调用父组件handle方法
  3. <my-click :my-age="age" :my-count="count" @click-count="handle"></my-click>
  4. </div>
  5. <script>
  6. const vm = new Vue({
  7. el: ".app",
  8. data() {
  9. return {
  10. age: 28,
  11. count: 0,
  12. };
  13. },
  14. components: {
  15. myClick: {
  16. props: ["myAge", "myCount"],
  17. template: `
  18. <div>
  19. <p>我的年龄是{{myAge}}</p>
  20. <button @click="$emit('click-count',1)">click:+{{myCount}}</button>
  21. </div>
  22. `,
  23. },
  24. },
  25. methods: {
  26. handle(value) {
  27. this.count += value;
  28. console.log(this.count);
  29. },
  30. },
  31. });
  32. </script>
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:组件之间的通信,其实还有其它方式的,有空多看看vue官网
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