一. vue传参的方式主要有以下几种:
- props传参:
父组件:
<children :child="father" />
或 <children xxx /> //只有属性没有值, 这种情况 props 若指定类型是 Boolean 则接收到的是 true
子组件props接收的三种方法:
props:[],
props: {xx: Number, xxx: String},
props: {
xx: {
type:Number, // 可选
required: true,// 可选
default:0,// 可选
// 返回值不是 true,会警告
validator(val) { return val === 10}
}
}
- 子组件传父组件 (通过子组件去触发在父组件上定义的方法)
父组件:
<children @child="child" />
methods: {
child(acceptChildParams) {
console.log(acceptChildParams, '收到子组件的传参')
}
}
子组件:
<div @click="click" />
methods: {
click() {
this.$emit('child', '传给父组件的参数')
}
}
- 插槽slot
插槽分为匿名插槽和具名插槽,主要有如下几种表现形式:
// 默认插槽,相当于是占位
---------------------------------------
<slot> </slot> // 定义默认插槽
// 使用
<div>123</div>
<!--另一种默认插槽的写法-->
<template v-slot:default></template>
-----------------------------------------
// 定义具名插槽
<slot name="header" ></slot>
<!--跑到具名插槽 header 中去-->
<template v-slot:header></template>
<!--缩写形式-->
<template #footer></template>
------------------------------------------
插槽传参:
<slot :user="user" name="header" ></slot> // 插槽传参
<!--获取子组件的值-->
<template v-slot:header="slot">{{slot.user}}</template>
<!--结构插槽值-->
<template v-slot:header="{user: person}">{{person}}</template>
<!--老式写法,可以写到具体的标签上面-->
<template slot="footer" slot-scope="scope"></template>
- root, children
1) $ref组件获取组件实例, 元素获取元素
2) $root 获取根组件
3) $parent 获取父组件
4) $children 获取所有子组件
- inject, project
//父组件 提供
project() {
return {
parent: this
}
}
子组件 注入 (关于此有几种写法,如下:)
inject: ['parent'],
inject: {parent: 'parent'}
inject: {
parent: {
from: 'parent',
default:''
}
}
- vuex 是专门为vue提供的一种全局状态数据管理库,具体可见官网vuex