vue-props

一、使用组件的三个步骤

Left.vue、Right.vue、 App.vue --》父子关系、兄弟关系

1.使用 import 语法导入需要的组件
2.使用 components 节点注册节点
3.以标签的形式使用刚才注册的组件
在这里插入图片描述

二、全局注册和私有子组件

  • 通过 components 注册的是私有子组件
  • 在 main.js 中 注册的vue.component() 是全局注
// main.js
// 导入需要被全局注册的组件
import Count from "@/components/Count";
Vue.component('MyCount',Count)

// Left.vue
<template>
  <div>
    left
    <hr>
    <MyCount></MyCount>
  </div>
</template>

三、组件的props

  • props 是组件的自定义属性,在封装通用组件的时候,合理地使用props可以极大的提高组件的复用性
    在这里插入图片描述
<template>
	<p>{
    
    {
    
     count }}</p>
	<button @click="count +=1">+1</button>
	<hr/>
// 1.可以结合 v-bind 使用
	<p>{
    
    {
    
     count }}</p>
	<button :init="9">+1</button>
</template>

<script>
	export default{
    
    
		props:[ 'init' ],
		data(){
    
    
			return {
    
    
// 2.props 是初始化值,只读不可写。
// 3.若要修改props的值,转存到data中,因为data中的数据都是可读可写的。
				count: this.init
		}
	}
}
</script>
  • default默认值,若外界使用有 props 的组件,没有传递自定义属性时,则默认值生效
props:[
	init:{
    
    
		default: 0
	}
]
  • type 类型:指定自定义属性的类型
props:[
	init:{
    
    
		default: 0,
		type: Number // String Array Object
	}
]
  • required:必填项,即用了有 props 的组件,必须使用当前自定义属性

四、使用案例

写文章时,用户自定义标题

猜你喜欢

转载自blog.csdn.net/weixin_52905182/article/details/127696476
今日推荐