在前端開發中,咱們經常會運用到「組件庫」。在main入口中引入組件庫,就能夠很輕鬆的在頁面中引入,並作一些基本的配置,如樣式,顏色等。只須要在引入的組件中寫入特定的屬性,就可以定義。html
例如:element-ui組件庫中使用switch開關,有個屬性active-color是設置「打開時」的背景色。change事件是觸發狀態的事件。前端
<el-switch v-model="value" :active-color="activecolor" @change="touchSwitch"> </el-switch> <script> export default { data() { return { value: true, activecolor: '#13ce66' } }, methods: { touchSwitch () { // 這裏入方法 } } }; </script>
咱們分析上面的代碼
首先咱們能夠看到active-color
是將特定的數據傳給組件,也就是父傳子組件。
其次是@change
雖然監聽的是改變事件,可是語法糖依然是$emit
,什麼emit咱們在之後的文章中會講到,就是「拋出事件」。vue
這就分爲組件的最基本功能:element-ui
那組件的使用咱們知道了,經過active-color傳入參數,經過@來接收事件。
因此,咱們來探究一下組件的內部結構是什麼樣的?函數
我寫了一個小模型,是一個顯示標題的小按鈕,經過div包裹。ui
<!-- type-box.vue --> <template> <div class="box" @click="ai_click(title)">{{title}}</div> </template> <script> export default { name: 'type-box', props: { title: { type: String, default: () => '' } }, methods: { ai_click (title) { this.$emit('ai_click', title) } } } </script> <style scoped> .box{ width: 250px; height: 100px; margin: 10px; border-radius: 10px; background-color: #3a8ee6; color: white; font-size: 25px; line-height: 100px; text-align: center; cursor: pointer; } </style>
使用方法:this
<!-- 父組件使用 --> <template> <div> <type-box title="演示盒子" @ai_click=「touch」></type-box> </div> </template> <script> import typeBox from './type-box' export default { components: { typeBox }, methods: { touch (data) { console.log(data) } } } </script>
經過props接收父組件傳遞過來的數據,經過工廠函數獲取一個默認值。code
經過this.$emit('ai_click', title)
告訴父組件,我要傳遞一個事件,名字叫「ai_click」,請經過@ai_click接收一下,而且我將title的值返回父組件。component
因此今天分析vue組件的3大核心概念的其中兩個——屬性和事件。
這篇文章只分析到應用場景,也是最簡單的組件。但願後續可以深刻了解vue的組件概念:屬性、事件和插槽。htm