Enumeration data usage in vue2
global usage
- Step 1: Create a folder dedicated to writing enumeration data and put the enumeration data js file in it
- The second step is to create the enumeration data js file and write the enumeration data in it, such as:
js文件中
const statustest = {
a: 0,
b: 1,
c: 2
}
- Step 3: Come to main.js to add references. import {statustest} from "@/........file location". Then mount Vue.prototype.statustest = statustest on the prototype object of the vue constructor
- Step 4: Use on the vue page,
组件中使用 示例
created(){
console.log(this.statustest.a) 返回的是 0
}
topical use
How to use enumeration data in VUE3
Features of enumeration type: , which has both type and value. Its value starts from 0 by default, and if the subsequent value is not defined, it will be accumulated.
- Role : Represents a set of explicitly optional values, similar to the literal type with the joint type.
- Explanation : An enumeration can define a set of constants. After using this type, the agreement can only use one of the constants in this set.
- Step 1: Create a folder dedicated to writing enumeration data and write ts files in it -- the general folder is named after enums
- Step Two: Remember to Speak Out
export enum IllnessTime {
//一周内
Week = 1, 1 === Week 且 Week === 1
/* 一月内 */
Month, 下面的都不用写 因为会从第一个开始累加
/* 半年内 */
HalfYear,
/* 半年以上 */
More
}
- Step 3: Import where it is used and import it on demand
For example
Type its characteristic case
Need to use type, add type when importing, import type {} from 'path'
No type is needed, no type is added when importing, import {} from 'path'
If the first corresponding value is not a number, then it will not be accumulated, and the value must be written, otherwise an error will be reported
<template></template>
<script setup lang="ts"> 这里用到了setup的语法糖!!!
/* 创建枚举数据 */
/* 可以发现 枚举数据是从头到尾从0 开始 往后的累加 */
enum Direction {
UP, //0 而且这里UP就是 0 0就是 UP
Down, //1
Left, //2
Right //3
}
/* 使用枚举数据 */
const res = (direction: Direction) => {
console.log(direction) //这里打印出来的值就是 0
}
/* 传入值进去 */
res(Direction.UP) //这里传进去的参数实际上就是 0
</script>
<style></style>
这是第二种案例
<template>
<div>
<h2>水果列表:</h2>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{
{ fruit }}
</li>
</ul>
</div>
</template>
<script lang="ts"> 这里没有用到setup !!
import { defineComponent } from 'vue';
enum Fruit {
Apple = '苹果',
Banana = '香蕉',
Orange = '橘子'
}
export default defineComponent({
data() {
return {
fruits: [Fruit.Apple, Fruit.Banana, Fruit.Orange]
};
}
});
</script>
The above is just a simple case. The standard usage is to create a folder dedicated to enumeration data under the src file and write it in it.