关键词搜索

源码搜索 ×
×

vue项目中的类

发布2022-08-29浏览1021次

详情内容

如题所示,vue项目中想提供类,该怎么写?

js其实并没有类,它只能用function来模拟类。如果用原生的js,要写一个类,可以这样写:

//类 
function Hi(){
	let hi = "hello world!";
	
	this.say = function(){
		console.log(hi);
	}
}

//使用类
let hi = new Hi();
hi.say();//hello world!
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

那在vue中怎么写呢?原生js的写法,我已经十分习惯了,用得很溜。但vue里面的写法,有点古怪:

1)定义

/src/utils/index.js

export class Hi {
  #hi;//#代表私有,不写就是公有,问你怕未
  constructor() {
    this.#hi = "hello world!";
  }

  say = () => {
    return this.#hi;
  };
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2)调用

//类定义位于文件 /src/utils/index.js
import * as tools from "@/utils";

const hi = new tools.Hi();
hi.say();
  • 1
  • 2
  • 3
  • 4
  • 5

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载