[Vue @Component] Pass Vue Render Functions as Props for Powerful Patterns

Render functions open up a world of customization and control by using pure JavaScript rather than Vue's templating language. When you need to pull off something super custom (or maybe you're just coming from React-land) you can turn to Render functions to save the day. This pattern demonstrates something very similar to a "bind" effect in a Vue template, but allows much finer control and customization.

We can use render props pattern in Vue as well:

const Selected = {
  props: {
    render: {
      default: h => null
    }
  },
  data() {
    return {
      selected: 0
    };
  },
  methods: {
    select(val) {
      this.selected = val;
    }
  },
  render() {
    return this.$props.render({
      selected: this.selected,
      select: this.select
    });
  }
};
export default {
  functional: true,
  render: (h, { props }) => (
    <div>
      <Selected
        render={({ select, selected }) => {
          return (
            <div>
              <label class="block text-grey-darker text-sm font-bold mb-2">
                Select Cat:
                <input
                  type="number"
                  value={selected}
                  onChange={event => select(+event.target.value)}
                  class="shadow appearance-none border rounded w-full py-2 px-3 text-grey-darker leading-tight"
                />
              </label>
              <div>
                <CatsList
                  names={props.names}
                  num={props.num}
                  select={select}
                  selected={selected}
                />
              </div>
            </div>
          );
        }}
      />
    </div>
  )
};

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/9369205.html