vue如何实现父子组件通信,以及非父子组件通信(待看)
http://www.cnblogs.com/luozhihao/p/5329440.html(vue特点及双向数据绑定)
https://vuefe.cn/v2/guide/components.html#
非父子关系
var vm = new Vue({
el: "#list",
ready: function(){
var _this = this;
var url = "http://192.168.1.111:8080/api/v2/getCommonCourses";
$.post(url,{"apiKey":apikey},function(data){
console.log(data);
if(data.status === 0) {
_this.$broadcast("parent-msg",data.data);
}
},"json");
},
components: {
courseList : List
},
});
new Vue({
el: "#condition",
data: {
isChecked: [1,0],
},
methods {
common: function() {
this.isChecked = true;
},
enterprise: function() {
this.idChecked = false;
}
}
})这样的两个组件之间的通讯应该通过共同的父组件,不管是通过refs方式:parent.$refs.list.<Method>
customer event方式: 先dispatch给父组件,再由父组件broadcast给子组件
props方式
这里推荐props方式。那么这里应该由三个组件:
FilterList (parent)
Condition (child)
List (child)并且由parent来享有数据:list和filterCondition,通过props传给child。
<div id="app">
<filter-list></filter-list>
</div>
<template id="filter-list-temp">
<div>
<h4>filter list</h4>
<condition :filter-text.sync="filterText"></condition>
<list :items="filteredItems"></list>
</div>
</template>
<template id="condition-temp">
<div>
<input v-model="filterText"/>
</div>
</template>
<template id="list-temp">
<div>
<p v-for="item in items">
{{item}}
</p>
</div>
</template>
Vue.component("condition", {
template: "#condition-temp",
props: ["filterText"]
});
Vue.component("list", {
template: "#list-temp",
props: ["items"]
})
Vue.component("filter-list", {
template: "#filter-list-temp",
data: function() {
return {
filterText: "",
items: ["Jack Yang","Angel","New York"]
}
},
computed: {
filteredItems: function() {
return this.$data.items.filter(function(item) {
return item.indexOf(this.$data.filterText) != -1;
}.bind(this));
}
}
})
new Vue({
el: "#app"
})父子通信
父子组件之间可以通过props进行通信: 组件的定义: 1.创建component类:
| 1 2 3 |
varProfile = Vue.extend({
template:"<div>Lily</div>";
})
|
2.注册一个tagnme: Vue.component("me-profile",Profile);//全局注册 局部注册:
| 1 2 3 4 5 6 7 |
varvm =
newVue({
el:"#todo",
components: {
"my-profile": Profile
},
...
}
|
模板注意事项: 因为 Vue 就是原生的DOM,所以有些自定义标签可能不符合DOM标准,比如想在
table 中自定义一个 tr,如果直接插入 my-component 不符合规范,所以应该这样写:
| 1 2 3 4 |
<table>
<tr is="my-component"></tr>
</table>
|
在子组件中有一个this.$parent和this.$root可以用来方法父组件和跟实例。(但是不推荐) Vue中子组件可以通过事件和父组件进行通信。向父组件发消息是通过this.$dispatch,而向子组件发送消息是通过this.$boardcast,这里都是向所有的父组件和子组件发送消息。 子组件:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
props: {
url: {
type: Array,
default:function()
{
return[]
}
}
},
methods: {
add:function() {
this.$dispatch("add",this.input);//这里就是向父组件发送消息
this.input ="";
}
}
|
父组件:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
data() {
return{
url: .....
}
},
events: {
add:function(input) {
if(!input)return
false;
this.list.unshift({
title: input,
done:false
});
}
}
|
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇: web前端页面性能优化小结
