Chuyển tới nội dung
Home » Vue Js Switch Case | How To Apply Switch In Vue Using Filters?

Vue Js Switch Case | How To Apply Switch In Vue Using Filters?

Vue Switch Case

v-else

You can use the

v-else

directive to indicate an “else block” for

v-if

:

template


Vue is awesome!

Oh no 😢

Vue is awesome!

A

v-else

element must immediately follow a

v-if

or a

v-else-if

element – otherwise it will not be recognized.

Complete Code

Here is a complete code created by combining the app.js and index.html to a single html file. This program can be run as a HTML file.



{{day1}} :

{{ day1 | dayType }}


{{day2}} :

{{ day2 | dayType }}


{{day3}} :

{{ day3 | dayType }}


{{day4}} :

{{ day4 | dayType }}


{{day5}} :

{{ day5 | dayType }}



In this article, we have discussed how to apply Switch in Vue using Filters with the help of two examples. In the first example, we checked weekdays/weekends using Switch and in the second example we checked day from numbers.

Kickstart Your Career

Get certified by completing the course

Get Started

  • 4 years ago
  • Zaid Bin Khalid
  • 5838 Views

In this session, you will learn how to use the switch and case statement to test expression with different values in JavaScript with the help of syntax and example.

Vue Switch Case
Vue Switch Case

The break Keyword

When JavaScript reaches a

break

keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

Using the Switch…Case Statement

The switch…case statement is used as an alternative statement to the if…else if…else statement; they almost work the same. The statement tests an expression or a variable against the series’s values until it finds a match. After that, it executes the block of code corresponding to that match.

The basic syntax of a switch…case, as shown below:

switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;

default:
// Code to be executed if x is different from all values
}

The following example will display the name of the day of the week.

var d = new Date();
switch(d.getDay()) {
case 0:
alert(“Today is Sunday.”);
break;
case 1:
alert(“Today is Monday.”);
break;
case 2:
alert(“Today is Tuesday.”);
break;
case 3:
alert(“Today is Wednesday.”);
break;
case 4:
alert(“Today is Thursday.”);
break;
case 5:
alert(“Today is Friday.”);
break;
case 6:
alert(“Today is Saturday.”);
break;
default:
alert(“No information available for that day.”);
break;
}

In one crucial way, the Switch…case is different from the if…else statement. The switch statement executes statement by statement or line by line. The JavaScript once find a case clause that evaluates to true, it does not only run the code corresponding to that case clause, but it also executes all the subsequent case clauses till the end of the switch block automatically.

To stop this, you must add a break statement after each case. The break statement will tell the JavaScript interpreter to break out of the switch…case statement block once it executes the code with the first true case.

In the case of the default clause, the break statement is not required when it finally appears in a switch statement. If another case statement is added to the switch statement, it prevents a possible programming error later. Although, it a good programming practice to terminate the last case or default clause in a switch statement with a break.

var d = new Date();
switch(d.getDay()) {
default:
alert(“Looking forward to the weekend.”);
break;
case 6:
alert(“Today is Saturday.”);
break;
case 0:
alert(“Today is Sunday.”);
}

Learn Switch Statements In 7 Minutes
Learn Switch Statements In 7 Minutes

Complete Code



{{day1}} :

{{ day1 | dayType }}


{{day2}} :

{{ day2 | dayType }}


{{day3}} :

{{ day3 | dayType }}


{{day4}} :

{{ day4 | dayType }}


{{day5}} :

{{ day5 | dayType }}



v-show

Another option for conditionally displaying an element is the

v-show

directive. The usage is largely the same:

template

Hello!

The difference is that an element with

v-show

will always be rendered and remain in the DOM;

v-show

only toggles the

display

CSS property of the element.


v-show

doesn’t support the element, nor does it work with

v-else

.

13. Cấu trúc switch case
13. Cấu trúc switch case

Example: Checking weekday/weekends using Switch

Copy paste the below code snipped in your vue project and run the vue project. You shall see the below output on the browser window.

  • FileName – app.js

  • Directory Structure — $project/public — app.js

// Defining the days to be checked to the index.html const parent = new Vue({ el: “#parent”, data: { day1: “Monday”, day2: “Thursday”, day3: “Sunday”, day4: “Friday”, day5: “Saturday”, }, filters: { dayType: function (day) { // Applying the filters with switch case. switch (day) { case “Monday”: case “Tuesday”: case “Wednesday”: case “Thursday”: case “Friday”: return “It is a Weekday.”; case “Saturday”: case “Sunday”: return “It is a Weekend.”; } }, }, });

  • FileName – index.html

  • Directory Structure — $project/public — index.html



{{day1}} :

{{ day1 | dayType }}


{{day2}} :

{{ day2 | dayType }}


{{day3}} :

{{ day3 | dayType }}


{{day4}} :

{{ day4 | dayType }}


{{day5}} :

{{ day5 | dayType }}


Run the following command to get the below output −

C://my-project/ > npm run serve

Example: Checking day from numbers

Copy paste the below code snipped in your vue project and run the vue project. You shall see the below output on the browser window.

  • FileName – app.js

  • Directory Structure — $project/public — app.js

// Defining the days to be checked to the index.html const parent = new Vue({ el: “#parent”, data: { day1: “1”, day2: “3”, day3: “6”, day4: “5”, day5: “7”, }, filters: { dayType: function (day) { // Applying the filters with switch case. switch (day) { case “1”: return “Monday”; case “2”: return “Tuesday”; case “3”: return “Wednesday”; case “4”: return “Thursday”; case “5”: return “Friday”; case “6”: return “Saturday”; case “7”: return “Sunday”; } }, }, });

  • FileName – index.html

  • Directory Structure — $project/public — index.html



{{day1}} :

{{ day1 | dayType }}


{{day2}} :

{{ day2 | dayType }}


{{day3}} :

{{ day3 | dayType }}


{{day4}} :

{{ day4 | dayType }}


{{day5}} :

{{ day5 | dayType }}


Run the following command to get the below output −

C://my-project/ > npm run serve

The Missing v-switch Component
The Missing v-switch Component

I’m running a switch/case that looks at the Vuetify breakpoint, but instead of just taking the name and giving me the int I want, it always ends up taking whatever the highest number is for the “limitSize” variable.

This is for a news slider I’m working on where, depending on the breakpoint, it shows either one, two, or three elements in the slider. I’ve tried giving the variable a default value, but that didn’t work. I’d preferably like it to go SM & down is 1, MD is 2 and LG & Up is 3, but I’m not sure what the right way to achieve that is. Any help would be greatly appreciated.

The following is the Switch/Case which sits inside a computed property. I’ve also attached an image of the current results of the code (Image is on MD window when I’d want 2)

VueJS


pageOfWhatsNews() { var limitSize; switch (this.$vuetify.breakpoint.name) { case "xs": limitSize = 1; case "sm": limitSize = 1; case "md": limitSize = 2; case "lg": limitSize = 3; case "xl": limitSize = 3; } var start = (this.currentPage - 1) * limitSize; var end = (this.currentPage - 1) * limitSize + limitSize; return this.whatsNews.slice(start, end); }

Start Date: 2023/1/23

Summary

This is a set of directives that allow the user to evaluate a condition based on whether or not it is a string number or array. The first one is called

Here is the link to a prototype that I created to make life easier https://stackblitz.com/edit/vitejs-vite-b6zaq8. It’s in the

Basic example

If the proposal involves a new or changed API, include a basic code example.

// This directive looks for the values in the case directives.

// This directive injects values for v-switch to use

Three
Ten
Six
NIne

This tells v-switch to render this div if any of the values sent to switch to use are not found.

This is the default
Motivation
Why are we doing this?

Having to use if statements for situations where you just want to know if a value is a certain value is tedious? When you have to use if statements to find out whether or not a value is in certain set of values you have to write

What use cases does it support?

It support’s cases where you need to find out if a string is of a certain value or a variable is a number. There are times where we use certain keywords to decide whether or not to render UI.


/* I have to write the promiseState variable repeatedly. I have to write the equal sign repeatedly. */

What is the expected outcome?

The community will be able to write code where a UI is rendered based on a small set of values in a simple and a reusable way.

Detailed design

This proposal involves three compile-time directives that are used for rendering.

V-switch

V switch does the following things

V-case

V case does the following things

V-default

V default does the following things

How it works with typescript

I don’t know how the Volar works but volar does support the use of conditional’s that emulate typescript features. The way v-switch would work is the same way that switch works in typescript. It would have the same features except in the template instead of in the DOM. If a union type is put inside of the switch statement the user will be forced to put it each value in the union in the case statements and write as many cases as there are in the union types.

This switch directive will work like this

Drawbacks

A breaking change is considered to because to a change that changes software regardless of whether or not something is removed or not? But developers will have to learn another alternative to evaluating conditions. Teachers of Vue will have to add new syntax to their curriculum.

Alternatives
What is the impact of not doing this?

People will have to write verbose if statements in order to evaluate values with a certain set of constraints.

Adoption strategy

This change is simply additive it will not force any changes to the ecosystem.

Unresolved questions

How will types be inferred I don’t how how that would work?

Can other Data Structures be supported as well?

Beta Was this translation helpful? Give feedback.

Replies: 2 comments 2 replies

The detailed design is based on

Limiting values to

Beta Was this translation helpful? Give feedback.

I just want it to exist. Don’t take the implementation too seriously. I don’t know enough about Vue to do a deeper version. The code that I wrote here is just a prototype. I saw no value it supporting data structures that use key-value pairs but if there are cases for it then I don’t mind supporting them.

Beta Was this translation helpful? Give feedback.

Well when I created the switch statement I wanted to only restrict it to only values not data structures and thought that there is no point in it supporting other kinds of values. I forgot that big-int even existed. I thought this version would be the realistic one. I have to change this RFC now. Thanks for pointing that out to me.

Beta Was this translation helpful? Give feedback.

How would you go about debugging this? also how would it work with typescript?

Beta Was this translation helpful? Give feedback.

Conditional Rendering

The JavaScript Switch Statement

Use the

switch

statement to select one of many code blocks to be executed.

Syntax

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

Example

The

getDay()

method returns the weekday as a number between
0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

This example uses the weekday number to calculate the weekday name:

case 0:

day = “Sunday”;

break;

case 1:

day = “Monday”;

break;

case 2:

day = “Tuesday”;

break;

case 3:

day = “Wednesday”;

break;

case 4:

day = “Thursday”;

break;

case 5:

day = “Friday”;

break;

case 6:

day = “Saturday”;

The result of day will be:

[Javascript căn bản] | bài 7:  Switch case trong lập trình | Nodemy
[Javascript căn bản] | bài 7: Switch case trong lập trình | Nodemy

v-ifv-show


v-if

is “real” conditional rendering because it ensures that event listeners and child components inside the conditional block are properly destroyed and re-created during toggles.


v-if

is also lazy: if the condition is false on initial render, it will not do anything – the conditional block won’t be rendered until the condition becomes true for the first time.

In comparison,

v-show

is much simpler – the element is always rendered regardless of initial condition, with CSS-based toggling.

Generally speaking,

v-if

has higher toggle costs while

v-show

has higher initial render costs. So prefer

v-show

if you need to toggle something very often, and prefer

v-if

if the condition is unlikely to change at runtime.

Medium

Default

You have to run this command for the installation via npm.


npm install v-switch-case

Or you can use script tag:

Node.js env (using webpack for example):

You can also use it with CDN:

If you wanted to employ this package in your project you can view its complete guide on Github.

Published at : 05-08-2021

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch project

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer’s Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

How to apply Switch in Vue using Filters?

Vue can be defined as a progressive framework for building the user interfaces. It has multiple directives that can be used as per the user needs. The basic core library is mainly focused on building the view layer only and is also easy to pick up other libraries or integrate with them.

The vue components provides the filter functionality to filter out the requests and response that lets the user to apply different formatting and transformations to the template dynamic data. Filters are used in two places : mustache interpolation and v-bind expressions.

Functions are appended in the end of a JavaScript expression and is denoted with a pipe operator.

For Ex −

{{ message | filter }}

JavaScript Framework Tier List
JavaScript Framework Tier List

v-else-if

The

v-else-if

, as the name suggests, serves as an “else if block” for

v-if

. It can also be chained multiple times:

template

Not A/B/C

Similar to

v-else

, a

v-else-if

element must immediately follow a

v-if

or a

v-else-if

element.

Common Code Blocks

Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:

Example

case 4:

case 5:

text = “Soon it is Weekend”;

break;

case 0:

case 6:

text = “It is Weekend”;

break;

default:

text = “Looking forward to the Weekend”;

Goodbye VS Code
Goodbye VS Code

The default Keyword

The

default

keyword specifies the code to run if there is no
case match:

Example

The

getDay()

method returns the weekday as a number between
0 and 6.

If today is neither Saturday (6) nor Sunday (0), write a default message:

case 6:

text = “Today is Saturday”;

break;

case 0:

text = “Today is Sunday”;

break;

default:

text = “Looking forward to the Weekend”;

The result of text will be:

The

default

case does not have to be the last case in a switch
block:

Example

default:

text = “Looking forward to the Weekend”;

break;

case 6:

text = “Today is Saturday”;

break;

case 0:

text = “Today is Sunday”;

If

default

is not the last case in the switch block, remember to end the default case with a break.

Medium

Default

Installation

npm:

npm install v-switch-case

yarn:

yarn add v-switch-case

Or using a script tag:

Use

Node.js env (using webpack for example):

From a CDN:

JavaScript Switch Statement

The

switch

statement is used to perform different actions based on different conditions.

Vue 3 & Composition API - Full Project
Vue 3 & Composition API – Full Project

v-if with v-for

Note

It’s not recommended to use

v-if

and

v-for

on the same element due to implicit precedence. Refer to style guide for details.

When

v-if

and

v-for

are both used on the same element,

v-if

will be evaluated first. See the list rendering guide for details.

05

Aug

lmiller1990 introduced a simple v-switch, v-case, and v-default directive set for Vue.js 2. If you have multiple tests cases for a particular expression. we can utilize the switch statement instead of writing multiple if/else statements in vue. So you can practice the v-switch-case in this condition. If you want something similar for Vue.js 3, you can check out v-switch.

You can view its live demo here:

Example:

Large

v-if on

Because

v-if

is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use

v-if

on a element, which serves as an invisible wrapper. The final rendered result will not include the element.

template


v-else

and

v-else-if

can also be used on .

Is Vue.js STILL relevant?
Is Vue.js STILL relevant?

Multiple Cases Sharing the Same Action

In a switch statement, each case value must be different from others or unique. Different cases don’t need to have a single action. Many situations can share the same work, as shown below:

var d = new Date();
switch(d.getDay()) {
case 1:
case 2:
case 3:
case 4:
case 5:
alert("It is a weekday.");
break;
case 0:
case 6:
alert("It is a weekend day.");
break;
default:
alert("Enjoy every day of your life.");
}

  • 4 years ago
  • Zaid Bin Khalid
  • 5838 Views

Strict Comparison

Switch cases use strict comparison (===).

The values must be of the same type to match.

A strict comparison can only be true if the operands are of the same type.

In this example there will be no match for x:

Example

switch (x) {

case 0:

text = "Off";

break;

case 1:

text = "On";

break;

default:

text = "No value found";

Python or JavaScript - Which One Should YOU Learn?
Python or JavaScript - Which One Should YOU Learn?

Keywords searched by users: vue js switch case

Câu Lệnh Switch - Case Trong Javascript | Học Javascript
Câu Lệnh Switch - Case Trong Javascript | Học Javascript
Javascript Switch Statement – With Js Switch Case Example Code
Javascript Switch Statement – With Js Switch Case Example Code
Câu Lệnh Switch - Case Trong Javascript | Học Javascript
Câu Lệnh Switch - Case Trong Javascript | Học Javascript
Vue Switch Case - Youtube
Vue Switch Case - Youtube
C]. Switch Case
C]. Switch Case
Javascript - Switch Statements - Youtube
Javascript - Switch Statements - Youtube
Câu Lệnh Switch Case Trong Php
Câu Lệnh Switch Case Trong Php

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *