您的位置:首页 > Web前端 > HTML

[IMWeb训练营作业]select组件 20170424

2017-04-24 14:39 489 查看
今天学习到组件的概念。父子组件的通信。可能有兄弟组件的通信。

直接放代码HTML核心部分。 
Tips && 知识点 

  1. component可以全局注册Vue.component(“name”,{options})或者局部注册↓↓
new Vue({**components**:
{
'name': {options},
'name': {options}
}
})
1
2
3
4
5
6
1
2
3
4
5
6

但是局部注册的组件只能在该作用域下使用。==>推荐自己测试下。

  2. 在component下同样又data属性,但是不同于Vue实例的data属性是一个对象,component的data必须是函数,因为对象是深copy.

  3.v-for指令支持(list,index)两个参数。可以很方便取到当前遍历的数据的index值。同样如果是object,可以(value, key, index)三个参数。

  4.通过$parent.$children可以方便在兄弟组件间读写数据。

在 Vue.js 中,父子组件的关系可以总结为 props down, events up 。父组件通过 props 向下传递数据给子组件,子组件通过 events 给父组件发送消息。

  5.父组件通过自定义属性向自组件传值,必须显示声明props: [“attrName”],这样子组件才能获取到。 

  6.子组件通过$emit(event,[…args])方法触发当前实例上的事件,把事件沿着作用域链向上派送。
<div id="app">
<!-- 组件 select,可自定的一个是组件里button的value值 ,另1个是子组件ul里li的各项内容。通过select组件就是 :ul-text="arr" -->
<custom-select class="select" btn-value="城市名" :ul-text="citys"></custom-select>
<custom-select class="select" btn-value="空气质量" :ul-text="AQIs"></custom-select>
<custom-select class="select" btn-value="倒序排名" :ul-text="ranking"></custom-select>
<!-- 其中子组件的接口数据可以有 v-bind:lists="arr"提供 <custom-ul v-bind:lists="XX"></custom-ul>-->
</div>
1
2
3
4
5
6
7
1
2
3
4
5
6
7

js部分
Vue.component("custom-select",{
props: ["btn-value","ul-text"],
data() { //因为有多个组件,data不能是对象。因为对象是深度copy
return {
ulShow: true,
inputValue: ""
}
},
template:
`<div>
<input type="text" :value="inputValue" disabled>
<input type="button" :value="btnValue" @click="ulShow = !ulShow">
<custom-ul :lists="ulText" v-show="ulShow" @receive="showLiText"></custom-ul>
</div>`,
// 父组件在使用子组件的地方用 v-on 来监听子组件触发的事件:
methods: {
//当子组件的触发了li的点击事件,通过$emit去触发receive事件。
showLiText(index) {
//通过$parent $children等操作多个组件同时changeValue
//TODO 把它们关联起来组件
//test
// for (var i = 0; i < this.$parent.$children.length) {
//  this.$parent.$children[i].inputValue = this.$parent.citys[index];
// }

this.$parent.$children[0].inputValue = this.$parent.citys[index];
this.$parent.$children[1].inputValue = this.$parent.AQIs[index];
this.$parent.$children[2].inputValue = this.$parent.ranking[index];
}
}
})

Vue.component("custom-ul",{
props: ["lists"],
template:
`<ul><li v-for="(listText, listIndex) in lists" @click="showLiText(listIndex)">{{listText}}</li></ul>`,
//通过v-for提供index参数。方便同步修改三者数据
methods: {
showLiText(index){
//触发当前实例上的事件,把事件沿着作用域链向上派送。
this.$emit("receive", index)
}
}
})
效果图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  select 通信 html