父子組件之間可以通過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 }); } }