vue 自定义组件 + 函数式组件
自定义组件一、思路1、定义子组件2、父组件中引入3、注册4、父组件传参,子组件通过props接收5、父组件自定义组件标签中内容,子组件slot接收二、示例:父组件传入数值,子组件对应渲染h1~h6标签父组件Fa.vue<template><div id="fa"><Son :type="2"></Son><...
·
自定义组件
一、思路
1、定义子组件
2、父组件中引入
3、注册
4、父组件传参,子组件通过props接收
5、父组件自定义组件标签中内容,子组件slot接收
二、示例:父组件传入数值,子组件对应渲染h1~h6标签
父组件Fa.vue
<template>
<div id="fa">
<Son :type="2"></Son>
</div>
</template>
<script type='text/ecmascript-6'>
import Son from "@/components/Son.vue";
export default {
name: "Fa",
components: {
Son,
},
};
</script>
<style>
</style>
子组件Son.vue
<template>
<div>
<h1 v-if="type === 1">
<slot></slot>
</h1>
<h2 v-if="type === 2">
<slot></slot>
</h2>
<h3 v-if="type === 3">
<slot></slot>
</h3>
<h4 v-if="type === 4">
<slot></slot>
</h4>
<h5 v-if="type === 5">
<slot></slot>
</h5>
</div>
</template>
<script>
export default {
props: ["type"]
};
</script>
缺点:如果是要动态配置100条数据,难道要v-if进行100条条件判断吗?
解决:函数式组件
函数式组件
一、引入
函数组件参数说明:
-
functional:true, // 约定是函数组件
-
render
(1)是一个函数
(2)函数组件,只有render方法
(3)render中,不能写template
(4) render函数默认接收两个形参,第一个是createElement(type,attrs:obj,children),非常类似jsx写法。 第二个参数是context,可以理解成:组件实例,这就要求对vue实例属性非常了解
常见如:
context.slots().default: slot内容,
context.props: 父子组件传递的属性
二、代码:
Fa.vue
<template>
<div id="fa">
<Son :type="4">8880008</Son>
</div>
</template>
<script type='text/ecmascript-6'>
import Son from "@/components/Son.js";
export default {
name: "Fa",
components: {
Son,
},
};
</script>
<style>
</style>
Son.js(函数组件)
export default {
functional:true,
render(h,context){
let t = 'h' + context.props.type;
return <t>{context.slots().default}</t>;
}
};
更多推荐
已为社区贡献3条内容
所有评论(0)