写一个VSCode snippets 代码片段

在上篇文章中(基于element-ui 搭建管理后台_夜跑者的博客-CSDN博客_elementui搭建后台)

我们基于element-ui搭建了一个通用的管理后台,在网络模块,对接口进行了封装,get, post请求如下所示:

    this.$http
      .get({ urlKey: "iot-getAsset", params: {} })
      .then((res) => {
        console.log("iot-getAsset res is: ", res);
      })
      .catch((err) => {
        console.error("iot-getAsset err is: ", err);
      });


    this.$http
      .post({ urlKey: "iot-getAsset", data: {} })
      .then((res) => {
        console.log("iot-getAsset res is: ", res);
      })
      .catch((err) => {
        console.error("iot-getAsset err is: ", err);
      });

这是两段通用网络接口代码,每个请求都这么写。我们能不能做个小工具方便的输入这些通用的代码片段呢?当然可以的。有经验的前端工程师基本上都安装了类似这样的VSCode插件。所以我们自定义的这个通用代码片段当然可以用VSCode插件来实现。为这2段代码片段写个VSCode插件有点杀鸡焉用牛刀的感觉。有没有更轻量的实现方案呢?VSCode 提供了snippets来实现。

1. 创建snippets文件

VSCode 编辑器 File -> Preferences -> Configure User Snippets   回车  选择New Snippets

2. 书写代码片段

{
	// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
	// Placeholders with the same ids are connected.
	// Example:
	// "Print to console": {
	// 	"scope": "javascript,typescript",
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
	"http get shortcut": {
		"scope": "javascript, typescript",
		"prefix": "vhttpget",
		"body": ["this.\\$http.get({urlKey: '$1', params: {}}).then(res => {console.log('$1 res is: ', res)}).catch(err => {console.error('$1 err is: ', err)})"],
		"description": "a http get short cut"
	},
	"http post shortcut": {
		"scope": "javascript, typescript",
		"prefix": "vhttpost",
		"body": ["this.\\$http.post({urlKey: '$1', data: {}}).then(res => {console.log('$1 res is: ', res)}).catch(err => {console.error('$1 err is: ', err)})"],
		"description": "a http post short cut"
	},
}

按注释进行书写代码片段就可以了,语法请参考:Snippets in Visual Studio Code

我们在.vue 中的

你可能感兴趣的:(前端工程化,vue.js,前端,javascript)