vue父子组件通信

父子组件之间可以通过props进行通信:

组件的定义:

1.创建component类:

var Profile = Vue.extend({
                   template: "<div>Lily</div>"; 
               })

  

2.注册一个tagnme:

Vue.component("me-profile",Profile);//全局注册

局部注册:

var vm = new Vue({
  el: "#todo",
  components: {
    "my-profile": Profile
  },
  ...
}

  

模板注意事项:

因为 Vue 就是原生的DOM,所以有些自定义标签可能不符合DOM标准,比如想在 table 中自定义一个 tr,如果直接插入 my-component 不符合规范,所以应该这样写:

<table>
  <tr is="my-component"></tr>
</table>
 

  

在子组件中有一个this.$parent和this.$root可以用来方法父组件和跟实例。(但是不推荐)

Vue中子组件可以通过事件和父组件进行通信。向父组件发消息是通过this.$dispatch,而向子组件发送消息是通过this.$boardcast,这里都是向所有的父组件和子组件发送消息。

子组件:

props: {
              url: {
                         type: Array,
                         default: function() {
                              return []               
                         }
                    } 
          },
 methods: {
    add: function() {
      this.$dispatch("add", this.input); //这里就是向父组件发送消息
      this.input = "";
    }
  }

  

父组件:

data() {
         return {
            url:   .....
          }  
     },
 events: {
    add: function(input) {
      if(!input) return false;
      this.list.unshift({
        title: input,
        done: false
      });
    }
  }