This is the third day of my participation in Gwen Challenge
Yesterday I released my first Vue component seriously written, if you are interested, you can take a look: Yesterday, the basic functions of the component (including amplification, abbreviation, rotation, restore) have been completed, and today, plus the download, although the download seems to have no use, right click save as can be, but the download write write found a lot of knowledge points, For example, to download files from different SRC addresses (httpURL,base64, local address), I will post the code in a moment, you can see ~ then I will configure the project a little bit, upload it to NPM, For other projects or friends who need to use (whether you use it or not, I feel my component is very good, hahaha ~).
1. Download function realization
// utils/index.js
/ / blob downloaded
export async function downFile(url, fileName = "download") {
try {
let blob = null;
// Local image network image base64 image processing
if (url.startsWith("http")) {
blob = await getBlob(url);
} else if (url.startsWith("data:image")) {
let mime = getBase64Type(url);
blob = mime ? dataURLtoBlob(url, mime) : dataURLtoBlob(url);
} else if (url.startsWith("/")) {
blob = await getBlob(window.origin + url);
} else {
return;
}
let a = document.createElement("a");
a.download = fileName;
a.href = window.URL.createObjectURL(blob);
a.click();
} catch (error) {
console.log(error); }}// Convert Base64 to BLOB
export function dataURLtoBlob(base64, mimeType = "image/png") {
let bytes = window.atob(base64.split(",") [1]);
let ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], { type: mimeType });
}
// Convert web urls to bloBs
export function getBlob(url) {
return new Promise((resolve, reject) = > {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () = > {
if (xhr.status == 200) {
resolve(xhr.response);
} else{ reject(); }}; xhr.send(); }); }// Get the base64 file type
export function getBase64Type(base64) {
let index0 = base64.indexOf(":");
let index1 = base64.indexOf(";");
let mime = "";
if(index0 ! = = -1&& index1 ! = = -1) {
mime = base64.slice(index0 + 1, index1);
}
return mime;
}
Copy the code
2. Release components
Component registration utility functions
// Import components
import imgLargeMode from "@/components/img-large-mode";
// Install method for use with vue.use () registration
const install = (Vue, option) = > {
// Create a constructor to generate a Vue instance
const componentInstance = Vue.extend(imgLargeMode);
// Define the instantiation object
let currentComponent = null;
// Instantiate the object to mount the component under body
const initInstance = () = > {
currentComponent = new componentInstance();
let componentEL = currentComponent.$mount().$el;
document.body.appendChild(componentEL);
};
// Define the user to use the method, hang to the Vue
Vue.prototype.$_openLargeMode = {
show(opt) {
initInstance();
returncurrentComponent.show(opt); }}; };if (typeof window! = ="undefined" && window.Vue) {
install(window.Vue);
}
export default {
install,
imgLargeMode
};
Copy the code
package.json
{
"name": "img-large-mode"."version": "0.1.0 from"."main": "./dist/img-large-mode.umd.min.js"."author": "Tmier"."description": "Vue based Big Picture Pattern Components"."keywords": [
"img-large-mode"."img-large"."large-mode"]."repository": {
"type": "git"."url": "https://github.com/itmier/img-large-mode"
},
"license": "MIT"."files": [
"dist"]."private": false."scripts": {
"serve": "vue-cli-service serve"."build": "vue-cli-service build"."package": "vue-cli-service build --target lib --name img-large-mode --dest dist ./src/components/index.js"."lint": "vue-cli-service lint"
},
"dependencies": {... },"devDependencies": {... }}Copy the code
Package. json (package.json)
Name: component name, package name, must be unique
Version: specifies the version number. This parameter is mandatory
Main: Entry function that starts the project file
If the package is installed by the user, require(‘foo-lib’) returns the module.exports property of the file listed in the main field when the user executes it
Author: the author
Description: describe
Keywords: keywords
License: license
Repository: A repository in which code is stored
Private: Default true, set to false when publishing a package, otherwise NPM will refuse to publish it
Files: is an array of files describing the items to include when installing a package as a dependency. If you declare a folder in an array, the files in that folder are also included. Some special files and directories are also included or excluded, whether they exist in the file array or not.
The following files, whether set or not, always contain: * 'package.json' * 'README' * 'CHANGES'/' CHANGELOG '/' HISTORY '*' LICENSE '/' NOTICE '* The file in The' main ' Field the following files are always ignored: * `.git` * `CVS` * `.svn` * `.hg` * `.lock-wscript` * `.wafpickle-N` * `.*.swp` * `.DS_Store` * `._*` * `npm-debug.log` * `.npmrc` * `node_modules` * `config.gypi` * `*.orig` * `package-lock.json`(use shrinkwrap instead)Copy the code
Add a new command to scripts that I think I should note:
"package": "vue-cli-service build --target lib --name img-large-mode --dest dist ./src/components/index.js"
Copy the code
Usage: vue cli - service build [options] [entry | pattern] options: - mode specified environment mode (default: production), dest specifies the output directory (default: Dist) - modern geared to the needs of modern browsers with automatic back to build applications -- target app | lib | wc | wc - async (default: app) - library name or the name of the Web Components mode (default: Package. The json"name"Field or entry filename) --no-clean Don't clean target directory before building project --report generates report-html to help analyze package contents --report-json generates report-.json to help analyze package contents --watch Listening for file changesCopy the code
Build command build target library name img-large-mode output directory dist function entry
PS: This entry can be a.js or a.vue file. If no entry is specified, SRC/app.vue is used.
After the configuration is complete, the NPM release ~ is next
NPM distribution package
npm login // Enter the username and password to log in to NPMNPM run package NPM publishCopy the code
Ok, successful release, done ~
Almost. I installed my own package on my home computer while I was writing this article, and then realized I had it with mevue
.vuex
.vue-router
Is there something I don’t have configured? I installed itelement-ui
, found that it does not install vUE related library, there is no big guy to give advice ~
3. Looking forward to
Improve the function of the component, the following can be thought of at present, can be added to see:
- Support array List, pictures can be realized on the next view
- 像
ant design
The samemodal
Animation Effect to add animation to the picture mask
Refer to the article: segmentfault.com/a/119000002…