1 组件left和组件right中的子组件count互不影响、单行代码函数简写
<template>
<div>
<h5>Count组件h5>
<p>count的值是:{{count}}p>
<button @click="add">+1button>
<button @click="count += 1">+1button>
div>
template>
<script>
export default {
data(){
return{
count: 0
}
},
methods: {
add(){
this.count+=1
}
}
}
script>
<style lang="less">
style>
2 组件的props
2-1 需求:期望组件left中count的初始值为5,组件right中count的初始值为9
2-2 props自定义属性
2-3 结合v-bind使用自定义属性
3 props是只读的,可以通过data修改但不能在其本身props上直接改
<template>
<div>
<h5>Count组件h5>
<p>count的值是:{{count}}p>
<button @click="count += 1">+1button>
<button @click="show">打印 thisbutton>
div>
template>
<script>
export default {
/*
props 是"自定义属性",允许使用者通过自定义属性,为当前组件指定初始值
自定义属性的名字,是封装者自定义的(只要名称合法即可)
props 中的数据,可以直接在模板结构中被使用,比如{{init}}
注意:props 是只读的,不要直接修改 props 的值,否则终端会报错
*/
props: ['init'],
data(){
return{
count: this.init
}
},
methods: {
add(){
this.count+=1
},
show(){
console.log(this)
}
},
}
script>
<style lang="less">style>
4 props的default默认值
5 props的type值类型
6 props的required必填项
7 源码
<template>
<div>
<h5>Count组件h5>
<p>count的值是:{{count}}p>
<button @click="count += 1">+1button>
<button @click="show">打印 thisbutton>
div>
template>
<script>
export default {
/*
props 是"自定义属性",允许使用者通过自定义属性,为当前组件指定初始值
自定义属性的名字,是封装者自定义的(只要名称合法即可)
props 中的数据,可以直接在模板结构中被使用,比如{{init}}
注意:props 是只读的,不要直接修改 props 的值,否则终端会报错
*/
// props: ['init'],
props: {
init: {
// 如果外界使用 Count 组件的时候,没有传递 init 属性,则默认值生效
default: 0,
// 规定init 的值类型必须是 Number 数字
type: Number, //可选Boolean\String\Array\Object等类型
// 必填项校验
required: true
}
},
data(){
return{
count: this.init
}
},
methods: {
add(){
// 把 props 中的 init 值,转存到 count 上
this.count+=1
},
show(){
console.log(this)
}
},
}
script>
<style lang="less">style>
<template>
<div class="left-container">
<h3>Left 组件h3>
<hr>
<MyCount :init="5">MyCount>
div>
template>
<script>
export default {}
script>
<style lang="less">
.left-container {
padding: 0 20px 20px;
background-color: orange;
min-height: 250px;
flex: 1;
}
style>
<template>
<div class="right-container">
<h3>Right 组件h3>
<hr>
<MyCount :init="9">MyCount>
div>
template>
<script>
export default {}
script>
<style lang="less">
.right-container {
padding: 0 20px 20px;
background-color: lightskyblue;
min-height: 250px;
flex: 1;
}
style>