- Vue.js 2.x by Example
- Mike Street
- 365字
- 2021-07-02 20:00:26
v-if
The most basic example of this would be the v-if directive – determining a value or function if the block should be displayed.
Create a Vue instance with a single p inside the view and a data key, isVisible, set to false.
View:
Start off with the view code as the following:
<p id="app">
<p>Now you see me</p>
</p>
JavaScript:
In the JavaScript, initialize Vue and create an isVisible data property:
const app = new Vue({
el: '#app',
data: {
isVisible: false
}
});
Right now, your Vue app would be displaying the contents of your element. Now add the v-if directive to your HTML element with the value of isVisible:
<p id="app">
<p v-if="isVisible">Now you see me</p>
</p>
Upon pressing save, your text should disappear. That is because the tag is being conditionally rendered based on the value, which is currently false. If you open up your JavaScript console and run the following code, your element should reappear:
app.isVisible = true
v-if doesn't just work with Boolean true/false values. You can check whether a data property is equal to a specific string:
<p v-if="selected == 'yes'">Now you see me</p>
For example, the preceding code checks whether a selected data property is equal to the value of yes. The v-if attribute accepts JavaScript operators, so can check not equals, bigger, or less than.
The danger here is that your logic starts to creep into your View away from your ViewModel. To combat this, the attribute also takes functions as a value. The method can be as complicated as required but ultimately must return a true if you wish to show the code and a false if not. Bear in mind that if the function returns anything other than a false value (such as 0 or false) then the result will be interpreted as true.
This would look something like this:
<p v-if="isSelected">Now you see me</p>
And your method could be as this:
isSelected() {
return selected == 'yes';
}
If you don't wish to completely remove the element and only hide it, there is a more appropriate directive, v-show. This applies a CSS display property rather than manipulating the DOM – v-show is covered later in the chapter.
- 大學(xué)計(jì)算機(jī)應(yīng)用基礎(chǔ)實(shí)踐教程
- ASP.NET Core 5.0開(kāi)發(fā)入門(mén)與實(shí)戰(zhàn)
- MATLAB圖像處理超級(jí)學(xué)習(xí)手冊(cè)
- HTML5+CSS3基礎(chǔ)開(kāi)發(fā)教程(第2版)
- INSTANT Sencha Touch
- HTML5+CSS3網(wǎng)站設(shè)計(jì)基礎(chǔ)教程
- 從0到1:Python數(shù)據(jù)分析
- Python Data Analysis Cookbook
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)原理(第2版)
- Swift語(yǔ)言實(shí)戰(zhàn)晉級(jí)
- Python從入門(mén)到精通(第3版)
- 并行編程方法與優(yōu)化實(shí)踐
- Getting Started with Python
- Java并發(fā)實(shí)現(xiàn)原理:JDK源碼剖析
- 程序員必會(huì)的40種算法