今天学习到组件的概念。父子组件的通信。可能有兄弟组件的通信。
直接放代码HTML核心部分。
Tips && 知识点
1. component可以全局注册Vue.component(“name”,{options})或者局部注册↓↓
new Vue({**components**:
{
'name': {options},
'name': {options}
}
})
但是局部注册的组件只能在该作用域下使用。==>推荐自己测试下。
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">
<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>
</div>
js部分
Vue.component("custom-select",{
props: ["btn-value","ul-text"],
data() {
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>`,
methods: {
showLiText(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>`,
methods: {
showLiText(index){
this.$emit("receive", index)
}
}
})
效果图: