父组件给子组件传参时,使用
props
参数对象接收,该参数可以是数组类型,也可以是对象类型(当需要对props进行类型限制和验证时)
Vue.component('my-component',{
template: `
组件
组件内容
`,
props:{
// 基础的类型检验(null 可以匹配任意类型
propA: Number,
// 多个可选类型
propB: [String,Number],
// 必填的字符串类型
propC: {
type: String,
required: true
},
// 带有默认值的数值
propD: {
type: Number,
default: 100
},
// 带有默认值的对象(数组同理)
propE: {
type: Object,
// 对象或数组默认值必须为带返回值的函数
default(){
return {}
}
},
// 自定义验证函数
propF: {
validator: function (value){
// 这个值必须匹配一下字符串中的一个
return ['success','warning','dange'].indexOf(value) !== -1
}
}
}
})
注意:props中使用驼峰标识时,在传参时需要使用
-
分割,如myData
在传参时,应该写成my-data
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<title>Documenttitle>
<style>
style>
head>
<body>
<div id="app">
<cpn1 :cmessages="messages" :c-number="number">cpn1>
div>
<template id="cpnC1">
<div>
{{cnumber}}
<h2>{{cmessages.title}}h2>
<p>{{cmessages.content}}p>
div>
template>
<script>
// 子组件对象
const cpnC1 = {
template: '#cpnC1',
props: {
cNumber: {
type: Number, // 参数类型为数字
default: 0, // 默认值为0
required: false // 是否必须传参
},
cmessages: {
type: Object,
default() { // 对象或数组时,default必须为一个有返回值的方法
return {}
},
required: true // 是否必须传参
}
}
}
// 父组件
const app = new Vue({
el: '#app',
data: {
number: 102212,
messages:{
title:'父传子',
content:'父组件向子组件传参'
}
},
components: { // 注册子组件
cpn1: cpnC1
}
})
script>
body>
html>
需要使用
this.$emit()
进行触发事件
this.$emit()
发射对应指令
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<title>Documenttitle>
<style>
style>
head>
<body>
<div id="app">
<cpn1 @clickme="childEvent">cpn1>
div>
<template id="cpnC1">
<div>
<button @click="btnClick(item)" v-for="item in cateData" style="margin:10px;">
{{item.name}}
button>
div>
template>
<script>
// 子组件对象
const cpnC1 = {
template: '#cpnC1',
data() {
return {
cateData: [
{ id: 1, name: '服装' },
{ id: 2, name: '家用电器' },
{ id: 3, name: '数码产品' },
{ id: 4, name: '零食' }
]
}
},
methods: {
btnClick(item) { // 子组件触发的函数
// this.$emit('clickme',item) 第一个产生为自定义事件名称(注意事件名称不支持驼峰命名方式),第二个参数为传递参数
this.$emit('clickme', item);
}
}
}
// 父组件
const app = new Vue({
el: '#app',
data: {
},
components: { // 注册子组件
cpn1: cpnC1
},
methods: {
childEvent(arges) { // 父组件中定义一个方法,用于子组件调用
console.log(arges); // arges 为子组件传递的参数
}
}
})
script>
body>
html>