IMWeb训练营作业-仿select组件

来源:互联网 发布:小型数据库管理系统 编辑:程序博客网 时间:2024/05/16 19:45

惯例,先放在线链接和效果gif。

http://xzchen.github.io/project/vue/select/
展示自己的select组件的gif图


今天学习到组件的概念。父子组件的通信。可能有兄弟组件的通信。

直接放代码HTML核心部分。
Tips && 知识点
  1. component可以全局注册Vue.component(“name”,{options})或者局部注册↓↓

new Vue({**components**:     {        'name': {options},        'name': {options}    } })

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

  2. 在component下同样又data属性,但是不同于Vue实例的data属性是一个对象,component的data必须是函数,因为对象是深copy。==>在上一篇博客toDoList的HTML注释部分也有写到。http://blog.csdn.net/qq_38222938/article/details/70184992

  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>

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)        }    }})

1 0