📜  Vue.js | v-else 指令(1)

📅  最后修改于: 2023-12-03 15:05:53.299000             🧑  作者: Mango

Vue.js | v-else Directive

In Vue.js, the v-else directive is used to toggle between two separate blocks of content based on a condition.

Syntax

The syntax for v-else directive is as follows:

<div v-if="condition">
    Block A
</div>
<div v-else>
    Block B
</div>

Here, the v-else directive is used to specify the block of content that should be displayed if the condition in the preceding v-if directive is false.

Example

Let's consider the following example:

<div id="app">
    <p v-if="loggedIn">
        You are logged in.
    </p>
    <p v-else>
        Please log in to continue.
    </p>
</div>

In the above example, if the loggedIn variable is true, the first paragraph element will be displayed. Otherwise, the second paragraph element will be displayed instead.

Code Demo

Here's a code demo to illustrate the use of v-else directive:

<div id="app">
    <button v-on:click="toggle">
        Toggle
    </button>
    <div v-if="show">
        Block A
    </div>
    <div v-else>
        Block B
    </div>
</div>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            show: true
        },
        methods: {
            toggle: function () {
                this.show = !this.show;
            }
        }
    });
</script>

In this code demo, we have a button that toggles the show variable between true and false. Based on this variable, the v-if and v-else directives are used to toggle between the two blocks of content.

Conclusion

The v-else directive is a simple yet powerful way to toggle between two blocks of content in Vue.js. Whether you are displaying different components or simply toggling between different renderings of the same component, v-else can help streamline your code and make for a more efficient use of resources.