做網站銷售iis搭建網站
1.什么是prop?
- 定義:組件標簽上注冊的一些自定義屬性
- 作用:向子組件傳遞數(shù)據(jù)
- 特點
- 可以傳遞任意數(shù)量的prop
- 可以傳遞任意類型的prop
2.prop校驗
為了避免亂傳數(shù)據(jù),需要進行校驗
完整寫法?
將之前props數(shù)組的寫法,改為對象的寫法
值得注意的是這個非空校驗,指的是萬一忘記傳值(忘了在標簽中寫自定義屬性)
僅類型校驗(最常用)
prop & data的異同點
共同點:都可以給組件提供數(shù)據(jù)
區(qū)別:
- data的數(shù)據(jù)是自己的 ->? ?想咋改咋改
- prop的數(shù)據(jù)是外部的 ->? ?不能直接改,要遵循 單向數(shù)據(jù)流
案例:加減器
?
數(shù)據(jù)count是父組件的,子組件的加減按鈕的功能不能直接count++ count--了,需要子傳父的寫法
- App.vue?
<template><div class="app"><BaseCount :Count="count" @CountAdd="CountAdd" @CountSub="CountSub"></BaseCount></div>
</template><script>
import BaseCount from "./components/BaseCount.vue"
export default {components: {BaseCount,},data() {return {count: 999,}},methods: {CountAdd(newCount){this.count = newCount;},CountSub(newCount){this.count = newCount;},}
}
</script><style></style>
- BaseCount.vue
<template><div class="base-count"><button @click="requestSub">-</button><span>{{ Count }}</span><button @click="requestAdd">+</button></div>
</template><script>
export default {props: {Count: Number,},methods: {requestSub() {this.$emit('CountSub',this.Count - 1);},requestAdd() {this.$emit('CountAdd',this.Count + 1);}}
}
</script><style></style>
單向數(shù)據(jù)流
由上面案例可以得出,父組件的prop數(shù)據(jù)的更新,會單向向下流動,影響到子組件
?