vue插件开发

一、export、export default、module.exports的区别

1、export和export default属于es6规范:

在同一个文件里面可以有多个export, 一个文件里面只能有1个export default 

//a.js

export const test = 'aaa';

export const a = function(){};


//b.js

const test = 'aaa';
export default test;

使用import 引入的方式也有点区别:

使用export时,用import引入相应的模块名字一定要和定义的名字一样,而使用export default时,用import引入模块名字可以不一样。

import {test, a} from 'a';

import aa from 'b';

另外如果使用webpack 的require引入 export default返回的模块时,需要额外写default   

var test = require('b').default; 

2、module.exports是cmd规范

(1)CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。

module.exports = {
  x: 1,
  y: 2
};
// 或者
module.exports.x = 1;
module.exports.y = 2;
// 或者
exports.x = 1;
exports.y = 2;

使用require来加载模块

let user = require('./user.js');
console.log( `username: ${user.x}`);      // 使用模板语言,注意:这里的不是分号

(2)common.js定义模块

定义:

define('common'. function () {
	return {
		initCart: function () {
			console.log('common init cart');
		}
	}
})

使用:common是请求的返回值

require(['./common.js'], function (common) {
	common.initCart();
})

二、搭建基于express的开发环境

1、全局安装express生成器

cnpm i -g express-generator

2、查看版本

express --version
4.16.0

3、生成express项目

express express          // express+项目名

4、安装依赖

E:\workspace\xampp\htdocs\demo\snowshop>cd express

E:\workspace\xampp\htdocs\demo\snowshop\express>cnpm install

5、运行

E:\workspace\xampp\htdocs\demo\snowshop\express>node ./bin/www

或者:

E:\workspace\xampp\htdocs\demo\snowshop\express>npm run start

打开:http://localhost:3000/

经历的步骤:因为路由是/所以

(1)在app.js中有:定义的是一级路由

var indexRouter = require('./routes/index');
app.use('/', indexRouter);

(2)会进入routes文件夹中的index.js,会执行以下:定义的是二级路由

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

(3)render会到views文件夹中,找到index.jade打开,显示在页面上

三、跨域

当后端提供接口的时候,使用axios来请求

axios不支持跨域,所以在config/index.js中配置:当请求goods的时候,代理到。。:3000的域名上

proxyTable: {
      '/goods': {
        target: 'http://localhost:3000'
      }

四、vue插件的开发

1、初始化文件

lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/vue-toast
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (vue-toast)
version: (1.0.0)
description: this is a toast for mobile phone
entry point: (index.js)
test command:
git repository:
keywords:
author: xueer
license: (ISC)
About to write to E:\workspace\xampp\htdocs\demo\vue-toast\package.json:

{
  "name": "vue-toast",
  "version": "1.0.0",
  "description": "this is a toast for mobile phone",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "xueer",
  "license": "ISC"
}


Is this ok? (yes)

2、静态部分

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
	<title>Document</title>
	<style type="text/css">
		.container {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 2000;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.toast {
			width: 180px;
			height: 60px;
			line-height: 60px;
			background: rgba(0, 0, 0, .61);
			color: white;
			text-align: center;
			border-radius: 10px;
			font-size: 18px;
		}
	</style>
</head>
<body>
	<section class="container">
		<div class="toast">hello, toast</div>
	</section>
</body>
</html>

3、既然是vue插件,当然要用vue写了,所以将静态文件拆到vue文件中,./lib/toast.vue

<template>
	<section class="container">
		<div class="toast" :class="[visible?'fade-in':'fade-out']">{{ message}}</div>
	</section>
</template>

<script>
	export default {
		data () {
			return {
				message: 'hello, toast',
				visible: false
			}
		}
	}
</script>

<style>
	.container {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 2000;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.toast {
			width: 180px;
			height: 60px;
			line-height: 60px;
			background: rgba(0, 0, 0, .61);
			color: white;
			text-align: center;
			border-radius: 10px;
			font-size: 18px;
		}
		.fade-in {
			animation: fade-in 0.3s;
		}
		.fade-out {
			animation: fade-out 0.3s;
		}
		@keyframes fade-in {
			0% { opacity: 0; transform: scale(0.7); }
			100% { opacity: 1; transform: scale(1); }
		}
		@keyframes fade-out {
			0% { opacity: 1; transform: scale(1); }
			100% { opacity: 0; transform: scale(0.7); }
		}
</style>

4、建一个入口文件./lib/index.js

import ToastComponet from './toast.vue'

let Toast = {}
Toast.install = function () {}              // 一定要有install函数,

export default Toast;

5、编写index.js

import ToastComponent from './toast.vue'

let Toast = {}
// 一定要有install函数,传入vue参数和options
Toast.install = function (Vue, options) {
	// 给原型加$toast方法
	Vue.prototype.$toast = function (message, option) {
		// 1、相当于继承组件,得到export中的
		const ToastController = Vue.extend(ToastComponent);
		// 2、创建一个实例,挂载到...,$mount就相当于new Vue({ el: '..' })中的el挂载
		var instance = new ToastController().$mount(document.createElement("div"));
		instance.message = message;   // 赋值
		install.visible = true;    // 可见

		// 多长时间消失
		setInterval( () => {
			instance.visible = false;
			document.body.removeChild(instance.$el);   // $el就是上面挂载的元素,移除掉
		}, 3000);

	}
	// 扩展show方法,以show方法调用,也可以扩展其他方法
	Vue.prototype.$toast['show'] = function (message, option) {
		Vue.prototype.$toast(message, option);
	}
}

export default Toast;

6、对于参数的处理(完整版)

import ToastComponent from './toast.vue'

let Toast = {}

// 一定要有install函数,传入vue参数和options
Toast.install = function (Vue, options) {
	// 默认的参数
	var opt = {
		duration:3000
	};
	// 将传入的options覆盖或填充默认的opt,全局的
	for (var key in options) {
		opt[key] = options[key];
	}
	// 给原型加$toast方法
	Vue.prototype.$toast = function (message, option) {
		// 局部的覆盖全局的
		if (typeof option === 'object') {
			for (var key in option) {
				opt[key] = option[key];
			}
		}
		
		// 1、相当于继承组件,得到export中的
		const ToastController = Vue.extend(ToastComponent);
		// 2、创建一个实例,挂载到。。teElement("div"));$mount就相当于new Vue({ el: '..' })中的el挂载
		var instance = new ToastController().$mount(document.createElement('div'));
		instance.message = message;   // 赋值
		instance.visible = true;    // 可见
		// 3、将挂载的元素添加进去
		document.body.appendChild(instance.$el);
		// 多长时间消失
		setTimeout( () => {
			instance.visible = false;
			document.body.removeChild(instance.$el);   // $el就是挂载的元素,移除掉
		}, opt.duration);
	}
	// 扩展show方法,以show方法调用,也可以扩展其他方法
	Vue.prototype.$toast['show'] = function (message, option) {
		Vue.prototype.$toast(message, option);
	}

	Vue.prototype.$toast['info'] = function (message, option) {
		Vue.prototype.$toast(message, option);
	}
}
// 相当于注册vue插件,使用use之后,便执行了install
if (window.Vue) {
	Vue.use(Toast);
}

export default Toast;

7、webpack打包

(1)安装依赖

$ cnpm install vue vue-loader webpack webpack-cli css-loader vue-template-compiler vue-style-loader babel-loader babel-core babel-preset-env --save-dev

(2)新建webpack.config.js,并配置

const path = require('path');
const {VueLoaderPlugin} = require('vue-loader');

module.exports = {
	entry: './src/lib/index.js',
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'vue-toast.js',
		libraryTarget: 'umd',   // 以什么格式打包,UMD可以打包成cmd、AMD格式
		library: 'VueToast'    // 打包之后的扩展名
	},
	module: {
		rules: [
			{
				test: /\.vue$/,
				loader: 'vue-loader',
				exclude: path.resolve(__dirname, 'node_modules'),
			},
			{
				test: /\.js$/,
				loader: 'babel-loader',
				exclude: path.resolve(__dirname, 'node_modules'),
				query: {
					presets: ['env']
				}
			},
			{
				test: /\.css$/,
				loader: 'vue-style-loader!css-loader'
			}
		]
	},
	plugins: [
		new VueLoaderPlugin()
	]
}

8、测试,在外面的index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
	<title>Document</title>
	<script type="text/javascript" src='../node_modules/vue/dist/vue.js'></script>
	<script type="text/javascript" src="../dist/vue-toast.js"></script>
</head>
<body>
	<div id="app">
		<a href="javascriipt:void(0);" @click="toast">点击淡出Toast</a>
	</div>

	<script type="text/javascript">
		new Vue({
			el: '#app',
			methods: {
				toast () {
					this.$toast.show('您好,toast');
				}
			}
		});
	</script>
</body>
</html>

9、通过npm发布插件

(1)首先去npm官网注册账号:https://www.npmjs.com

(2)在搜索框中搜索你要发布的名称,是package.json中的name,如果没有,可以发布,否则改名

(3)进入项目根目录,登录npm

lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/vue-toast
$ npm adduser

填写刚刚注册的用户名、密码、和邮箱

可通过下面来查看当前用户

lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/vue-toast
$ npm whoami

(4)发布

lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/vue-toast
$ npm publish
以上便可以将插件成功发布

(5)添加README.md文件,让别人知道怎么用

# vue-toast-snow

a mobile toast plugin for vue

## Usage

import VueToast from 'toast'

Vue.use(VueToast)

this.$toast.show("Hello Toast")
(6)然后重新发布,但是一定要 修改版本号,不然不能发布,在package.json中的version
lenovo@DESKTOP-NL309GS MINGW64 /e/workspace/xampp/htdocs/demo/vue-toast
$ npm publish



















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值