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>
六 运行效果
原文地址:https://www.cnblogs.com/sea-breeze/p/11563545.html
时间: 2024-10-06 05:29:45