1563941119
One of the most common components in web applications is the modal dialog. Vue modals are rather easy to create and work with, and in this tutorial, we’ll show you how!
Let’s dive right in.
For this tutorial, we will be using the Eclipse IDE with the CodeMix plugin installed.
We can now create our application using the CodeMix Project Wizard. We’ll be using the latest version of all the tech libraries and stacks as at the time of this writing. To create a new Vue Project, navigate to File > New > Project > CodeMix > Vue Project. Ensure you choose the, “A Vue CLI-built application” option in the wizard before clicking Finish.
Once the project is completed, open the integrated Terminal+ for the project using Ctrl/Cmd + Shift + P, and executing the command, “Terminal: Create New Integrated Terminal”. If you have more than one project in your workspace, you will be asked to select your project in the command palette before the Terminal is opened.
In the Terminal, run the following commands to install the required Node modules.
npm install
After the installation is complete, you can serve the application right away, find your application in the Servers view and use the context menu run action to start serving it.
In the components
folder, create a file named AppModal.vue
. You can do this by using the New > Vue file wizard accessible from the project’s context menu. We’ll create a very basic component for now.
Note: For more on CodeMix’s Vue capabilities
<template>
<div>
<div>
<h1>Modal heading</h1>
</div>
<hr>
<div>
<h1>Modal content</h1>
</div>
<hr>
<div>
<button>Close</button>
</div>
</div>
</template>
<script>
export default {
name: 'app-modal',
};
</script>
In App.vue
, we import the AppModal
component like below:
<template>
<div id="app">
<h1>Vue Modal Tutorial</h1>
<app-modal></app-modal>
</div>
</template>
<script>
import AppModal from './components/AppModal';
export default {
components: {
AppModal
}
}
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
If you’re using a recent version of CodeMix, you’ve probably noticed a new browser pane beside the editor – this pane will update after you save your changes, to show you the current state of the app after your changes have been rebuilt. Your application will now look like this:
Obviously this is no good as the modal is open over our app – we’re going to add a condition under which the modal will show, and a button to display it.
<template>
<div id="app">
<h1>Vue Modal Tutorial</h1>
<app-modal v-if="showModal"></app-modal>
<button @click="openModal" v-if="!showModal">Open Modal</button>
</div>
</template>
<script>
import AppModal from './components/AppModal';
export default {
components: {
AppModal
},
data() {
return {
showModal: false
}
},
methods: {
openModal() {
this.showModal = true;
}
},
}
</script>
Here we created our modal template with two div
tags and one button
element. The button
is used to open our modal. In our second div
tag, we added a v-if=isOpen
directive so that our modal will only display if the isOpen
property is true.
Vue.js slots are handy when we want to embed content inside child components. So let’s allow the App.vue
component to pass DOM elements into the AppModal.vue
component. At the same time, we’ll take the opportunity to add some style to our modal, so replace the contents of AppModal.vue
with the source below.
<template>
<div class="modal" v-if="showModal">
<div v-if="showModal" class="modal-content">
<div class="modal-header">
<slot name="header"></slot>
</div>
<hr>
<div class="modal-body">
<slot name="body"></slot>
</div>
<hr>
<div>
<button>Close</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'app-modal',
props: {
showModal: Boolean
}
};
</script>
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 600px;
max-width: 100%;
height: 400px;
max-height: 100%;
background: #FFFFFF;
box-shadow: 2px 2px 20px 1px;
overflow-x: auto;
display: flex;
flex-direction: column;
}
</style>
We’ll modify the template section of App.vue
with the template below, to actually pass data to our modal component.
<template>
<div id="app">
<h1>Vue Modal Tutorial</h1>
<button @click="openModal" v-if="!showModal">Open Modal</button>
<app-modal v-if="showModal" :showModal=showModal>
<div slot="header">
<h3 class="modal-title">
CodeMix
</h3>
</div>
<div slot="body">
<p>
With CodeMix, you can join the modern web movement right from your Eclipse IDE!
</p>
</div>
</app-modal>
</div>
</template>
<script>
We need to find a way for passing data from the child component back to the parent, so AppModal component can say, “Hey, App component, can you close this me?”.
We’ll implement a closeModal
method that will use $emit
for this purpose, and we’ll call this from the button, on click.
In AppModal.vue
, add the following to the scripts
section
methods: {
closeModal() {
this.$emit('clicked');
}
},
And we’ll modify our button
to call this method:
<button @click="closeModal">Close</button>
Back in App.vue
we need to receive the clicked event and close the modal, so add the following method to the methods section which already exists:
onChildClick () {
this.showModal = false;
}
And we’ll modify the reference to the app-modal
component to call the above method when receiving a clicked
event:
<app-modal v-if="showModal" :showModal=showModal @clicked="onChildClick">
This is how your app should finally look:
Here are two vue files in their entirety, just in case you missed something.
AppModal.vue
<template>
<div class="modal" v-if="showModal">
<div v-if="showModal" class="modal-content">
<div class="modal-header">
<slot name="header"></slot>
</div>
<hr>
<div class="modal-body">
<slot name="body"></slot>
</div>
<hr>
<div class="modal-footer">
<button @click="closeModal">Close</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'app-modal',
props: {
showModal: Boolean
},
methods: {
closeModal() {
this.$emit('clicked');
}
},
};
</script>
<style>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 600px;
max-width: 100%;
height: 400px;
max-height: 100%;
background: #FFFFFF;
box-shadow: 2px 2px 20px 1px;
overflow-x: auto;
display: flex;
flex-direction: column;
}
</style>
App.vue
<template>
<div id="app">
<h1>Vue Modal Tutorial</h1>
<button @click="openModal" v-if="!showModal">Open Modal</button>
<app-modal v-if="showModal" :showModal=showModal @clicked="onChildClick">
<div slot="header">
<h3 class="modal-title">
CodeMix
</h3>
</div>
<div slot="body">
<p>
With CodeMix, you can join the modern web movement right from your Eclipse IDE!
</p>
</div>
</app-modal>
</div>
</template>
<script>
import AppModal from './components/AppModal';
export default {
components: {
AppModal
},
data() {
return {
showModal: false
}
},
methods: {
openModal() {
this.showModal = true;
},
onChildClick () {
this.showModal = false;
}
},
}
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
In this article we’ve learnt how to create a modal dialog with Vue, and explored the use of named slots to distribute content between components.
You can download the source code from our GitHub repository here.
#vue-js #javascript #web-development
1656151740
Flutter Console Coverage Test
This small dart tools is used to generate Flutter Coverage Test report to console
Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):
dev_dependencies:
test_cov_console: ^0.2.2
flutter pub get
Running "flutter pub get" in coverage... 0.5s
flutter test --coverage
00:02 +1: All tests passed!
flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/ | | | | |
print_cov.dart | 100.00 | 100.00 | 88.37 |...,149,205,206,207|
print_cov_constants.dart | 0.00 | 0.00 | 0.00 | no unit testing|
lib/ | | | | |
test_cov_console.dart | 0.00 | 0.00 | 0.00 | no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing | 100.00 | 100.00 | 88.37 | |
---------------------------------------------|---------|---------|---------|-------------------|
If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE> The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...> A list of contains string for files without unit testing
to be excluded from report
-l, --line It will print Lines & Uncovered Lines only
Branch & Functions coverage percentage will not be printed
-i, --ignore It will not print any file without unit testing
-m, --multi Report from multiple lcov.info files
-c, --csv Output to CSV file
-o, --output=<CSV-FILE> Full path of output CSV file
If not given, "coverage/test_cov_console.csv" will be used
-t, --total Print only the total coverage
Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM> Print only the whether total coverage is passed MINIMUM value or not
If the value >= MINIMUM, it will print PASSED, otherwise FAILED
Note: it will ignore all other option (if any), except -m
-h, --help Show this help
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/ | | | | |
print_cov.dart | 100.00 | 100.00 | 88.37 |...,149,205,206,207|
lib/ | | | | |
test_cov_console.dart | 0.00 | 0.00 | 0.00 | no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing | 100.00 | 100.00 | 88.37 | |
---------------------------------------------|---------|---------|---------|-------------------|
It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/ | | | | |
print_cov.dart | 100.00 | 100.00 | 88.37 |...,149,205,206,207|
lib/ | | | | |
test_cov_console.dart | 0.00 | 0.00 | 0.00 | no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing | 100.00 | 100.00 | 88.37 | |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a - |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/ | | | | |
print_cov.dart | 100.00 | 100.00 | 88.37 |...,149,205,206,207|
lib/ | | | | |
test_cov_console.dart | 0.00 | 0.00 | 0.00 | no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing | 100.00 | 100.00 | 88.37 | |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b - |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/ | | | | |
print_cov.dart | 100.00 | 100.00 | 88.37 |...,149,205,206,207|
lib/ | | | | |
test_cov_console.dart | 0.00 | 0.00 | 0.00 | no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing | 100.00 | 100.00 | 88.37 | |
---------------------------------------------|---------|---------|---------|-------------------|
flutter pub run test_cov_console -c --output=coverage/test_coverage.csv
#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""
You can install the package from the command line:
dart pub global activate test_cov_console
The package has the following executables:
$ test_cov_console
Run this command:
With Dart:
$ dart pub add test_cov_console
With Flutter:
$ flutter pub add test_cov_console
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
test_cov_console: ^0.2.2
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:test_cov_console/test_cov_console.dart';
example/lib/main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console
License: BSD-3-Clause license
1661169600
Make Pop-Up Modal Window In Vanilla JavaScript
Learn how to create a simple responsive pop-up modal window using Vanilla JavaScript along with HTML and CSS with a bit of Flexbox.
Declare a <button> HTML element with an id open-modal.
<button id="open-modal">Open Modal Window</button>
The goal is when a user presses this button, the pop-up modal window will open.
Style the button using CSS Flexbox and centre it on the screen.
* {
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
button {
padding: 10px;
font-size: 1.1em;
background: #32bacf;
color: white;
border: none;
border-radius: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
cursor: pointer;
}
button:hover {
background: rgba(0, 0, 0, 0.7);
}
Normally, pop-up modal windows have overlays with a transparent darker background that covers the entire browser screen.
Define a div with an id model-overlay which will cover the entire screen.
<div id="modal-overlay">
<div>
Then, make it to full screen using height:100vh CSS property.
Bring it in front of the button by using position:absolute with a transparent background colour.
#modal-overlay {
width: 100%;
height: 100vh;
position: absolute;
background: rgba(0, 0, 0, 0.7);
}
I just added the border to see the boundaries of the modal-overlay element.
Create a div with an id modal inside the modal-overlay element, which will be an actually pop-up modal window that user interacts with.
<div id="modal-overlay">
<div id="modal">
</div>
<div>
Add CSS style to make it visible on the screen.
Adding width:100% and max-width:650px will make sure the width of the pop-up modal window won’t exceed when the browser width is more than 650px.
If the browser width is less than 650px, the pop-up modal window will stretch the width to fill the screen which is normally for mobile viewports.
#modal-overlay #modal {
max-width: 650px;
width: 100%;
background: white;
height: 400px;
}
Centre the pop-up modal window to the screen using Flexbox.
To do that, just add the three lines of Flexbox code to the modal-overlay which are
#modal-overlay {
...
display: flex;
align-items: center;
justify-content: center;
}
Now we have the basic pop-up modal window designed using CSS.
Make it visible when a user presses the open modal button.
To do that,
First, hide the modal overlay by default by changing its display property from flex to none.
#modal-overlay {
...
display: none; // Changed from flex to none
align-items: center;
justify-content: center;
}
Create a DOM reference to the open-modal button as well as the modal-overlay elements.
const openModalButton = document.getElementById("open-modal");
const modalWindowOverlay = document.getElementById("modal-overlay");
Attach a click event to the openModalButton with the callback arrow function showModalWindow.
const showModalWindow = () => {
modalWindowOverlay.style.display = 'flex';
}
openModalButton.addEventListener("click", showModalWindow);
Set the display property of the modalWindowOverlay to flex inside showModalWindow() function which will open up the modal window.
As you can see, there is no way we can close/hide the pop-up modalwindow after its became visible on the screen.
Let’s fix it!
Typically, there will be a close button on the top or bottom right side of the pop-up modal window.
Let’s add a close button on the bottom left side of the modal window.
Define header, content and footer HTML elements inside the pop-up modal window.
<div id="modal">
<div class="modal-header">
<h2>Modal Pop Up Window</h2>
</div>
<div class="modal-content">
<p>Modal Content</p>
</div>
<div class="modal-footer">
<button id="close-modal">Close</button>
<button>Save</button>
</div>
</div>
Generally, you’ll have two buttons on the footer of the pop-up modal window, which may be save and close.
Let’s push the buttons to the bottom using Flexbox.
Turn the display property of the pop-up modal window to flex and set the flex direction to column.
1600583123
In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.
Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.
This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.
Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.
Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.
“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You
#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js
1624226400
Bitcoin Cash was created as a result of a hard fork in the Bitcoin network. The Bitcoin Cash network supports a larger block size than Bitcoin (currently 32mb as opposed to Bitcoin’s 1mb).
Later on, Bitcoin Cash forked into Bitcoin SV due to differences in how to carry on its developments.
That’s Bitcoin Cash in a nutshell. If you want a more detailed review watch the complete video. Here’s what I’ll cover:
0:50 - Bitcoin forks
2:06 - Bitcoin’s block size debate
3:35 - Big blocks camp
4:26 - Small blocks camp
5:16 - Small blocks vs. big blocks arguments
7:05 - How decisions are made in the Bitcoin network
10:14 - Block size debate resolution
11:06 - Bitcoin cash intro
11:28 - BTC vs. BCH
12:13 - Bitcoin Cash (ABC) vs. Bitcoin SV
13:09 - Conclusion
📺 The video in this post was made by 99Bitcoins
The origin of the article: https://www.youtube.com/watch?v=ONhbb4YVRLM
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#bitcoin #blockchain #bitcoin cash #what is bitcoin cash? - a beginner’s guide #what is bitcoin cash #a beginner’s guide
1598685221
In this tutorial, I will show you how to upload a file in Vue using vue-dropzone library. For this example, I am using Vue.js 3.0. First, we will install the Vue.js using Vue CLI, and then we install the vue-dropzone library. Then configure it, and we are ready to accept the file. DropzoneJS is an open source library that provides drag and drops file uploads with image previews. DropzoneJS is lightweight doesn’t depend on any other library (like jQuery) and is highly customizable. The vue-dropzone is a vue component implemented on top of Dropzone.js. Let us start Vue File Upload Using vue-dropzone Tutorial.
Dropzone.js is an open-source library providing drag-and-drop file uploads with image previews. DropzoneJS is lightweight, doesn’t depend on any other library (like jQuery), and is highly customizable.
The vue-dropzone is a vue component implemented on top of Dropzone.js.
First, install the Vue using Vue CLI.
Go to your terminal and hit the following command.
npm install -g @vue/cli
or
yarn global add @vue/cli
If you face any error, try running the command as an administrator.
Now, we need to generate the necessary scaffold. So type the following command.
vue create vuedropzone
It will install the scaffold.
Open the project in your favorite editor. Mine is Visual Studio Code.
cd vuedropzone
code .
I am using the Yarn package manager. So let’s install using Yarn. You can use NPM, also. It does not matter.
yarn add vue2-dropzone
or
npm install vue2-dropzone
Okay, now we need to add one css file with the above package. Now, vue cli uses css loader, so we can directly import in the src >> main.js entry file.
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
import 'vue2-dropzone/dist/vue2Dropzone.css'
If importing css is not working for you, then you need to install that CSS file manually.
Copy this vue2Dropzone.css file’s content.
Create one file inside the src >> assets folder, create one css file called vuedropzone.css and paste the content there.
Import this css file inside src >> App.vue file.
<style lang="css">
@import './assets/vuedropzone.css';
</style>
Now, it should include in our application.
Our primary boilerplate has one ready-made component called HelloWorld.vue inside src >> components folder. Now, create one more file called FileUpload.vue.
Add the following code to FileUpload.vue file.
// FileUpload.vue
<template>
<div id="app">
<vue-dropzone id="upload" :options="config"></vue-dropzone>
</div>
</template>
<script>
import vueDropzone from "vue2-dropzone";
export default {
data: () => ({
config: {
url: "https://appdividend.com"
}
}),
components: {
vueDropzone
}
};
</script>
Here, our API endpoint is https://appdividend.com. It is the point where we will hit the POST route and store our image, but it is my blog’s homepage, so it will not work anyway. But let me import this file into App.vue component and see what happens.
// App.vue
<template>
<div id="app">
<FileUpload />
</div>
</template>
<script>
import FileUpload from './components/FileUpload.vue'
export default {
name: 'app',
components: {
FileUpload
}
}
</script>
<style lang="css">
@import './assets/vuedropzone.css';
</style>
Now, start the development server using the following command. It will open up URL: http://localhost:8080.
npm run serve
Now, after uploading the image, we can see that the image upload is failed due to the wrong POST request endpoint.
Install the Laravel.
After that, we configure the database in the .env file and use MySQL database.
We need to create one model and migration file to store the image. So let us install the following command inside the Laravel project.
php artisan make:model Image -m
It will create both the Image model and create_images_table.php migrations file.
Now, open the migrations file and add the schema to it.
// create_images_table.php
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image_name');
$table->timestamps();
});
}
Now, migrate the database table using the following command.
php artisan migrate
It creates the table in the database.
Now, we need to add a laravel-cors package to prevent cross-site-allow-origin errors. Go to the Laravel root and enter the following command to install it.
composer require barryvdh/laravel-cors
Configure it in the config >> app.php file.
Barryvdh\Cors\ServiceProvider::class,
Add the middleware inside app >> Http >> Kernel.php file.
// Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Barryvdh\Cors\HandleCors::class,
];
First, create an ImageController.php file using the following command.
php artisan make:controller ImageController
Define the store method. Also, create one images folder inside the public directory because we will store an image inside it.
Right now, I have written the store function that handles one image at a time. So do not upload multiple photos at a time; otherwise, it will break.
// ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
class ImageController extends Controller
{
public function store(Request $request)
{
if($request->file('file'))
{
$image = $request->file('file');
$name = time().$image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
}
$image= new Image();
$image->image_name = $name;
$image->save();
return response()->json(['success' => 'You have successfully uploaded an image'], 200);
}
}
Go to the routes >> api.php file and add the following route.
// api.php
Route::post('image', 'ImageController@store');
We need to add the correct Post request API endpoint in FileUpload.vue component.
// FileUpload.vue
<template>
<div id="app">
<vue-dropzone id="drop1" :options="config" @vdropzone-complete="afterComplete"></vue-dropzone>
</div>
</template>
<script>
import vueDropzone from "vue2-dropzone";
export default {
data: () => ({
config: {
url: "http://localhost:8000/api/image",
}
}),
components: {
vueDropzone
},
methods: {
afterComplete(file) {
console.log(file);
}
}
};
</script>
Now, save the file and try to upload an image. If everything is okay, then you will be able to save the image on the Laravel web server as well as save the name in the database as well.
You can also verify on the server side by checking the database entry and the images folder in which we have saved the image.
The only required options are url, but there are many more you can use.
For example, let’s say you want:
export default {
data: () => ({
dropOptions: {
url: "https://httpbin.org/post",
maxFilesize: 5, // MB
maxFiles: 5,
chunking: true,
chunkSize: 400, // Bytes
thumbnailWidth: 100, // px
thumbnailHeight: 100,
addRemoveLinks: true
}
})
// ...
}
Happy Coding !!!
Originally published at https://appdividend.com
#vue #vue-dropzone #vue.js #dropzone.js #dropzonejs #vue cli