<template> <div v-show="show" :class="`alert alert-${type} alert-dismissible`"> <button @click="close" type="button" class="close"><span>×</span></button> {{ msg }} </div> </template>
v-show 是一個條件渲染指令,它只切換元素 CSS 屬性的 display,這里當 show 值為 true 時,我們就顯示該元素。
<script> export default { name: 'Message', props: { // 是否顯示消息框 show: { type: Boolean, default: false }, // 消息框的類型 type: { type: String, default: 'success' }, // 消息 msg: { type: String, default: '' } }, watch: { show(value) { if (value) { this.$nextTick(() => { this.$el.scrollIntoView(true) }) } } }, methods: { close() { this.$emit('update:show', false) } } } </script>
props 是用來傳遞數據的,我們需要在子組件用 props 選項聲明它預期的數據,上面的代碼中我們聲明了 3 個屬性,並為其指定了 type 類型和 default 默認值,這樣我們就能在父組件上傳遞這些值了,就像下面的代碼一樣
<Message :show.sync="msgShow" :type="msgType" :msg="msg"/>
type 可以是以下的類型:
StringNumberBooleanFunctionObjectArraySymbol
關於偵聽器:
watch: { show(value) { if (value) { this.$nextTick(() => { this.$el.scrollIntoView(true) }) } } }
watch 選項提供了一個方法來響應數據的變化,在上面的代碼中,我們需要監聽 show 的新值 value,完整的傳參是 show(val, oldVal),val 是新值,oldVal 是舊值。當新值返回 true 時,我們將當前元素滾動到可視區域的頂部。
關閉事件:
close() { this.$emit('update:show', false) }
$emit 用於觸發當前實例上的事件,其第一個參數是事件名稱,后面還可以附加若干參數。當點擊關閉按鈕時,我們觸發一個 'update:show' 的事件,並附帶一個參數 false,用來關閉消息提示。(為什么事件名稱是 'update:show',我們稍后結合 props 進行講解。)
我們可以在組件模板內使用組件定義的 props,但我們不應該直接修改 props。要在組件內更新 props 選項的 show 值,需要顯式地觸發一個更新事件:
close() { // 可以觸發一個事件來更新 show this.$emit('update:show', false) // 不可以直接修改 show,這會導致 Vue 在控制台發出錯誤警告 this.show = false }
props 的綁定默認是單向的,我們要在組件內部更新 show 值,需要在父組件上添加 .sync 修飾符,以創建『雙向綁定』:
<Message :show.sync="msgShow"/>
上面的代碼會被 Vue 擴展為:
<Message :show="msgShow" @update:show="val => msgShow = val" />
因為父組件有 update:show 事件監聽,所以我們能在組件內部使用 $emit 來關閉消息提示:
close() { this.$emit('update:show', false) }
