vue2函数化组件

2018-05-02留

搜来搜去还是自己以前发的, 以前想写一个select的, 现在不清楚那时候的构思逻辑了,目前完成了select的写法,也运用在项目中,还有一点需要优化以后再贴过来。据目前的理解函数组建可以运用到无状态的上下文,举几个列子:右键菜单,radio,checkbox等。

--------------以下原帖内容---------------

版本

2.1.6

例子

https://jsfiddle.net/xzhwbb1o/2/

期望

I want to get the component item up component choice, but when functional , the parent is the #app, remove the functional is choice, is the default of this? I have read the document render, but did not find the relevant tips.

阅读 5.4k
2 个回答

哎,主要要写一个自定义的下拉框组件,直接用 $emit 也发不出事件,我现在在用jsx语法写,看着就蛋疼

choice.vue

<template>
  <div class="select" v-clickout="close">
    <div class="selection">
      <input type="text" v-model="value" ref="reference" @click="clickHandler" :placeholder="placeholder">
    </div>
    <drop placement="bottom" ref="drop" @select="select">
      <ul>
        <slot></slot>
      </ul>
    </drop>
  </div>
</template>

item.vue

export default {
  render: function(h) {
    return h('li', {
      on: {
        click: () => {
          this.$parent.select({id:this.value,name: $(this.$el).text()})
        }
      }
    }, this.$slots.default)
  },
  props: ['value', 'test']
};

index.html

模式一:
<choice v-model="qqq.b" test="" url="/groups/query" />

模式二:
<choice v-model="qqq.b" test="">
    <item value="online" class="classa classb">online</item>
    <item value="buffer">buffer</item>
</choice>

对于模式一来说很容易,直接在choice组件的dropslot遍历就好了.
但是模式二的话这个itemchoice组件无法直接把事件传递过来,所以怎么都行不通,所以我现在不打算跨组件写了,直接对choicerenderjsx进行编译了

大概就是这个样子

  async render(h) {
    console.log('render');
    if (this.$slots.default) {
      let temp = [];
      this.$slots.default.forEach(e => {
        if (e.tag != 'item') return;
        temp.push({
          value: e.data.attrs.value,
          name: e.children[0].text,
          class: e.data.staticClass
        })
      })
      this.list = temp;
    } else {
      let data = await this.$http.post(this.url);
      // this.list = _.p
    }
    return <div id="foo">
             <div class="selection">
               <input type="text" ref="reference" onClick={this.clickHandler}  placeholder={this.placeholder}/>
               <span class="fa-close"></span>
             </div>
             <drop placement="bottom" ref="drop">
               <ul>
                 {this.list.map(e =>
                   <li class={e.class} onClick={this.select.bind(this, e)}>{e.name}</li>
                 )}
               </ul>
             </drop>
           </div>

  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题