码迷,mamicode.com
首页 > 其他好文 > 详细

Vue 渲染函数

时间:2019-09-21 17:13:03      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:name   this   number   mil   ops   html   asc   nat   编译器   

 

Vue 推荐在绝大多数情况下使用模板来创建你的 HTML。然而在一些场景中,你真的需要 JavaScript 的完全编程的能力。这时你可以用渲染函数,它比模板更接近编译器。

 

一 项目结构

 

技术图片

 

二 App组件

 

<template>
  <div id="app">
    <fruit fruitName="Durian" :level="2">
      very  delicious!
    </fruit>
  </div>
</template>

<script>
import "./components/Fruit.js";
export default {
  name: "App"
};
</script>

<style lang="scss">
</style>

 

三 Fruit组件

 

import Vue from "vue";
import Durian from "./Durian.vue";
import Mongo from "./Mongo.vue";

Vue.component("fruit", {
  props: {
    fruitName: {
      type: String,
      required: true
    },
    level: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      shop: "水果店"
    };
  },
  render(createElement) {
    const { fruitName, level, shop, $slots, nativeClickHandler } = this;
    const ele = fruitName === "Durian" ? Durian : Mongo;
    return createElement(
      ele,
      {
        class: {
          favorFruit: true
        },
        style: "color:gold;font-style:italic;",
        attrs: {
          id: "favorFruit"
        },
        nativeOn: {
          click: nativeClickHandler
        },
        scopedSlots: {
          shop(props) {
            return createElement("h6", shop);
          }
        }
      },
      [createElement("h" + level, fruitName), $slots.default]
    );
  },
  methods: {
    nativeClickHandler() {
      console.log("native click");
    }
  }
});

 

四 Durian组件

 

<template>
    <div>
        <slot/>
        <slot name="shop"/>
    </div>
</template>
<script>
export default {
  name: "Durian"
};
</script>

 

五 Mongo组件

 

<template>
    <div>
        <slot/>
        <slot name="shop"/>
    </div>
</template>
<script>
export default {
  name: "Mango"
};
</script>

 

六 运行效果

 

技术图片

 

技术图片

 

Vue 渲染函数

标签:name   this   number   mil   ops   html   asc   nat   编译器   

原文地址:https://www.cnblogs.com/sea-breeze/p/11563545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!