Component registration and component value passing

Table of contents

Component Mechanism

Component registration

1. Global registration

2. Partial Registration

Component pass value

Parent-child component passing value

Sibling component pass value

Passing grandparents and grandchildren components - use provide and inject together


Component Mechanism

Components are one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulate reusable code, and are reusable Vue instances that can accept the same configuration items as new Vue except for the el attribute.

Component Features

1. Reusable. Components can be reused any number of times. 2. The data of the component must be a function, because if the data of the component is an object, then multiple identical components will point to the same reference address, and a change in one component will affect other components.

Component registration

1. Global registration

Syntax: Vue.component('component name', component)

Application scenario: choose global registration when the registration component is used in multiple components

    <div id="app">{
   
   {msg}}
        <!-- 3.组件使用 -->
        <my-b></my-b>
    </div>
    <script>
        // 1.定义组件
        let myB={
            template:`
            <div>{
   
   {msgB}}</div>`,
            data(){
                return {
                    msgB:'我是自定义组件B'
                }
            }
        }
        // 2.全局注册 --可以使用在任意组件内部
        Vue.component('my-b',myB)
        new Vue({
            el:'#app',
            data:{
                msg:'根组件'
            },
            methods:{}
        })
    </script>

2. Partial Registration

Syntax: components:{'component name':component}

Application scenario: Use local registration when only used in a certain component

    <div id="app">{
   
   {msg}}
        <!-- 3.组件使用 -->
        <my-a></my-a>
    </div>
    <script>
        // 1.定义一个组件
        let myA={
            template:`
            <div>{
   
   {msgA}}</div>`,
            data(){
                return {
                    msgA:'我是自定义组件'
                }
            }
        }
        new Vue({
            // 2.注册组件
            // 局部注册 --只能使用在注册了该组件的组件内部
            components:{
                'my-a':myA
            },
            el:'#app',
            data:{
                msg:'根组件'
            },
            methods:{}
        })
    </script>

Component pass value

Parent-child component passing value

Pass value from parent component to child component

1. Write the value to be passed in on the subcomponent tag

Static parameter passing

<div id="app">
    <!-- 静态传参 传入的参数类型永远是string-->
    <child msg="hello!"></child>
</div>
<script>
// 全局注册child组件
Vue.component('child', {
  // 声明props 接收父组件传递的值
  props: ['msg'],
  template: '<span>{
   
   { msg }}</span>'
})
// 创建根实例
new Vue({
  el: '#app'
})
</script>

2. The props attribute receives the value passed in by the parent component

Note: prop is one-way binding. When the properties of the parent component change, it will be transmitted to the child component, but not vice versa.

Dynamic parameter passing

Similar to using v-bind to bind HTML attributes to an expression, whenever the data of the parent component changes, the change is also propagated to the child component.

<div id="app">
		<!-- 1.在子组件标签上 写入传入得值 -->
		<!-- 动态传参 在前面加上: -->
		<my-a :age="true"  :sub1="undefined" :sub="null" :msg="250"></my-a>
	</div>
	<script>
		let myA={
			// 子组件可以对父组件得传值进行类型校验
			// 2.接收父组件传递的值
			// props:['msg1','msg','stu','age','obj'],
            // props可以是一个字符串数组,props也可以是一个提供带有验证需求的对象
			props:{
				age:{
					// 可以进行多个类型值得校验,age的类型是其中一种就不会报错
					type:[Number,String,Boolean],
					// 自定义校验器规则 val代表传入的值
					validator(val){
						return val>50
					}
				},
				msg:Number,
				sub:String,
				sub1:Number,
				stu:{
					type:Array,
					// 默认值 报错 Object/Array要一个工厂函数返回默认值
					// default:[4,5,6]
					default(){
						return [4,5,6]
					}
				}		
			},
			template:`
				<div>
					我是子组件
					{
   
   {sub1}}--{
   
   {typeof sub1}}
					{
   
   {sub}}--{
   
   {typeof sub}}
					{
   
   {age}}--{
   
   {typeof age}}
					{
   
   {stu}}--{
   
   {typeof stu}}
					{
   
   {msg}}
				</div>
			`,
			data(){
				return {}
			},
		};
		new Vue({
            // 局部注册组件
			components:{
				'my-a':myA
			},
			el:"#app",
		})
	</script>

The result is shown in the figure:  

 Because the value of age is true, the custom validator rule is not satisfied, so an error will be displayed on the console.

Passing value from child component to parent component

The child component passes the value to the parent component using the emission event (custom event)

1. The subcomponent emits a custom event through emit this.$emit (event name, passed value)

// 定义一个组件
let myA={
	template:`
		<div>
		    <button @click='toSend'>子传值给父</button>
		</div>
	`,
	data(){
		return {
			subMsg:'我是子组件A --我要给父组件传值'
		}
	},
	methods:{
		toSend(){
			this.$emit('my-event',this.subMsg)
		}
	}
}

2. Use the label custom event of the child component in the parent component

<div id="app">
    <my-a @my-event="handler"></my-a>
</div>

 3. Set the value of the child element to be passed to the parent element

new Vue({
    // 局部注册组件
	components:{
		'my-a':myA
	},
    // 将模板和实例绑定
	el:"#app",
	data:{
		msg:'我是父组件'
	},
	methods:{
		handler(a){
			console.log(a,'这是子组件的值');
		}
	}
})

Sibling component pass value

1. First declare an event bus Bus.js

import Vue from 'vue';
export default new Vue();

2. The brother component (Header) uses $emit to launch the event to carry parameters

<!-- 点击按钮给组件Footer传值 -->
<button @click="handler">传值给Footer</button>
methods:{
		handler(){
			Bus.$emit('toFoot',this.Footer)
		}
	}

3. Get the parameter $on('custom event name', (emitted data)=>{...}) passed in by the sibling component

created(){
		// {prototype:$emit() $on()}
		Bus.$on('toFoot',(a)=>{
			console.log(a,'这是Footer传给我得值');
		});
	}

Passing grandparents and grandchildren components - use provide and inject together

1. The data is passed by the ancestor component using the provide method

data(){
    return {
      msg:'我是祖先组件',
      a:12
    }
  },
  // 祖先组件使用provide方法提供传递得数据
  provide(){
    return {
      "msg":this.msg,
      "a":this.a
    }
  }

2. The data is injected by the grandson component using inject

<div>
	{
   
   {msgC}}-{
   
   {msg}}--{
   
   {a}}
</div>
<script>
data(){
	return {
		msgC:"底部组件得子组件"
	}
},
// 注入数据 
inject:['msg','a'],
}
</script>

Guess you like

Origin blog.csdn.net/qq_50748038/article/details/127055300
Recommended