v-if用string template時,要寫一個條件渲染,可以這麼做
{ {#if ok} }
< h1 >Yes< /h1 >
{ {/if} } 很麻煩吧!所以
Vue有提供v-if的寫法來簡化這個語法
< h1 v-if="ok">Yes< /h1 >也可以加
< h1 v-if="ok">Yes< /h1 > < h1 v-else>No< /h1 >群組化條件渲染
< template v-if="ok"> < h1 >Title< /h1 > < p >Paragraph 1< /p > < p >Paragraph 2< /p > < /template >
v-else< div v-if="Math.random() > 0.5">Now you see me< /div > < div v-else >Now you don't< /div >
v-else-if< div v-if="type === 'A'" >A< /div > < div v-else-if="type === 'B'" >B< /div > < div v-else-if="type === 'C'" >C< /div > < div v-else >Not A/B/C< /div >
templatetemplate有一種語法叫templaate,可以在條件渲染時,只換掉HTML的差異之處,而不是整個語法法換掉。
< template v-if = "loginType === 'username'" > < label > Username label > < input placeholder = "Enter your username" > < /template > < template v-else > < label > Email < /label > < input placeholder = "Enter your email address" > < /template >
loginType: {{loginType}}
template不過,還有另一種使用template的情況
若想要清掉整個HTML時,該怎麼辦呢?用key!!!
< template v-if="loginType === 'username'" > < label>Username< /label > < input placeholder="Enter your username" key="username-input" > <= 在這裡加key < /template > < template v-else > < label>Email< /label > < input placeholder="Enter your email address" key="email-input" > <= 在這裡加key < /template >
loginType: {{loginType}}
v-showcss的display:nonetemplatev-elsev-if vs v-show速度: v-show
因為v-if會真正的操作DOM使它真正的消失在HTML文件內。(慢)
而v-show只是讓DOM不出現在畫面,並不是不存在。元素總是會被渲染,只是用CSS切換。
v-if vs v-for優先權: v-for > v-if