Vue组件的props

108 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 21 天,点击查看活动详情 响应式数据的基本实现

组件三要素 props slog 以及 event,本篇主要讲解props校验的一些东西

props是什么

props 表示组件接收的参数。可以通过type、validator等方式对输入进行props的校验

vue组件props校验

props的type总共类型未

String Number Boolean Array Object Function Synbol

props1: String
props2: [String, Number]

对于type为Array 和Object 的默认值必须是函数返回

props3: {
    type: Number,
    default : 1
},
props3: { 
    type: Object, 
    default() { 
        return{ a: '1'}
    }}

类似于element 的size ,必须在固定的几个值里面的一个。这种校验我们必须自定义。 以下面type为例 type必须为'dash', 'light','default'三个字符串中的一个。所以我们校验的时候需要自己判断用户输入的是否在其中

utils.js增加通用的判断方法

/**
* @param value  用户输入的字符串
  @param validList  期望输入的字符串列表。
**/
export const oneOf = function(value, validList) {
	for (let i = 0; i < validList.length; i++) {
		if (value === validList[i]) {
			return true;
		}
	}
	return false;
}

然后在component里面使用。这样当使用f-button组件的时候,如果传入的字符串不在期望的数组中,就会给用户抛错。


<template>
	<view :class="'button-box  button-box-'+ buttonType" 
	</view>
</template>

<script>
	import {
		oneOf
	} from '../../utils/utils';
	export default {
		name: 'f-button',
		props: {
			buttonType: {
				type: String,
				validator(value) {
					return oneOf(value, ['dash', 'light','default']);
				},
				default: 'default',
			},
			title: {
				type: String,
				default: '',
			},

		},
		data() {
			return {

			}
		},
		methods: {
			onClick(e) {
				this.onTitleClicked && this.onTitleClicked(this.title, this.desc)
			}

		}
	}
</script>

<style lang="scss" scoped>
	
	.button-box-type1 {
		padding: 32rpx 0;

		.title {
			font-size: 34rpx;
			font-weight: 600;
			color: #111111;
			line-height: 46rpx;
		}
	}

	.button-box-type1 {
		padding: 32rpx 0;
		border-bottom: 1rpx solid #f2f2f2;
		

		.title {
			font-size: 28rpx;
			color: #333333;
		}

	}
</style>


为什么data是函数,而newView的时候可以是对象。

JS 里对象是引用关系,作用域没有隔离,而组件是需要被引用的,但是 new Vue 的实例是应用的顶部,是不会被复用的,因此不存在引用对象的问题。

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 21 天,点击查看活动详情 响应式数据的基本实现