Thứ Sáu, 4 tháng 2, 2022

NodeJS Express SocketIO – Chat message and send image

When it comes to NodeJS, Realtime must be thought of. Realtime here is to process the communication from client to server in real time.

NodeJS is an open source code widely used by thousands of programmers around the world. NodeJS can run on many different operating systems from Windows to Linux, OS X so that is also an advantage. NodeJS provides rich libraries in different form of Javascript Module which simplify programming and minimize time.

Here I will introduce the structure of realtime chat message application using NodeJS combined Express, Socket IO consists of two parts: server side, client side.


1. First, create a folder containing your source code and install modules.

– Create a folder containing your source code.

mkdir NodeJs-Express-SocketIO-SendImage

– Run [npm init] to initialize the source file, package.json. Select the js code file is index.js

cd NodeJs-Express-SocketIO-SendImage

npm init

– Install the module for use in NodeJS, it is: express ejs socketio

npm install express ejs socketio

– Now the content of your package.json file looks like this:

{
“name”: “NodeJs-Express-SocketIO-SendImage”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“ejs”: “^3.1.6”,
“express”: “^4.17.1”,
“socketio”: “^1.0.0”
}
}

– Create a public folder to store js and images files after being uploaded.

mkdir public

cd public

mkdir js

mkdir uploads

– Copy jquery.min.js to public/js folder or you can get it from cdn jquery

– Your code directory will now look like this:

NodeJs-Express-SocketIO-SendImage-source-path

Source path


2. Server side NodeJS

– In the index.js file:

var express = require (‘express’);
var app = express();
var fs = require(‘fs’);

app.use(express.static(__dirname + ‘/public’));

app.set(“view engine”, “ejs”);
app.set(‘views’, ‘views’);

var server = require(‘http’).Server(app);

var io = require(‘socket.io’)(server);
const port = process.env.PORT || 8080;
server.listen(port, () => console.log(`Listen on port ${port}…`));

io.on(‘connection’, function (socket) {
console.log(‘Connection ID: ‘ + socket.id);
socket.on(‘disconnect’, function () {
console.log(‘Disconect ID: ‘ + socket.id);
});

// The server listens to data from the client
socket.on(‘Client-sent-data’, function (data) {
// After listening to data, server emit this data to all clients
io.sockets.emit(‘Server-sent-data’, data);
});

// Handle image
socket.on(“sendImage”, function(data){
var guess = data.base64.match(/^data:image\/(png|jpeg);base64,/)[1];
var ext = “”;
switch(guess) {
case “png”  : ext = “.png”; break;
case “jpeg” : ext = “.jpg”; break;
default     : ext = “.bin”; break;
}
var savedFilename = “/uploads/” + randomString(10)+ext;
fs.writeFile(__dirname + “/public” + savedFilename, getBase64Image(data.base64), ‘base64’, function(err) {
if (err !== null)
console.log(err);
else
io.sockets.emit(“receiveImage”, {
path: savedFilename,
});
console.log(“Send image success!”);
});
});
})

app.get(‘/’, function(req, res) {
res.render(‘home’);
})

function randomString(length)
{
var text = “”;
var possible = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_”;

for( var i=0; i < length; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}

return text;
}

function getBase64Image(imgData) {
return imgData.replace(/^data:image\/(png|jpeg|jpg);base64,/, “”);
}


3. Client side NodeJS

– Use ejs to display Client side content. In the views folder, create home.ejs file

<!DOCTYPE html>
<html>
<head>
<title>NodeJS Express SocketIO – Chat message & send image</title>
<script type=”text/javascript” src=”js/jquery.min.js”></script>
<script type=”text/javascript” src=”socket.io/socket.io.js”></script>

<script type=”text/javascript”>
var socket = io(‘http://localhost:8080’);

// The client recevie the data from the server
socket.on(‘Server-sent-data’, function(data) {
$(‘#show-message’).append(‘<p>’ + data + ‘</p>’);
});

// The client send data to the server
$(document).ready(function () {
$(‘#send’).on(‘click’, function () {
var message = $(‘#message’).val();
socket.emit(“Client-sent-data”, message);
$(‘#message’).val(”);
document.getElementById(“message”).focus();
})

})

// Handle image
window.onload = function() {
document.getElementById(“file”).addEventListener(“change”, function(){
submitImage();
});
};

function submitImage(){
var selector = document.getElementById(“file”);
var img = document.getElementById(“preview”);

var reader = new FileReader();
reader.onload = function (e) {
// img.src = e.target.result;
// client send
socket.emit(“sendImage”, {base64:e.target.result});
}
reader.readAsDataURL(selector.files[0]);
}

// Client receive
socket.on(‘receiveImage’, function(data){
// document.getElementById(“showImage”).src = data.path;
var img = ‘<img id=”showImage” src=”‘ + data.path + ‘” width=”100″/>’;

$(‘#show-message’).append(img);
});
</script>
</head>

<body style=”width: 500px; margin: 0 auto;”>
<h2>Chat messages</h2>
<div id=”show-message”></div>
<div>
<p>
<textarea id=”message” rows=”5″ style=”width: 100%”></textarea>
</p>
<p>
Choose image:
<input id=”file” type=”file”>
<img id=”preview” width=”100″></img>
</p>

<button id=”send”>Send message</button>
</div>
</body>
</html>

 

And run in the browser:

NodeJs-Express-SocketIO-SendImage-client-side

Client side

 

4. Run demo NodeJS Express SocketIO, chat message and send image

– Now you run the web server using command: node index.js

node index.js

– Open two browsers to test, type in a message and choose a picture to send. When sending a message and selecting a photo in one of the screens, the received screen is also displayed

NodeJs-Express-SocketIO-SendImage-result

Result chat message

 

– In your command prompt

NodeJs-Express-SocketIO-SendImage-run

Result in console log

 

You check in the public/uploads folder, the images are saved.

Hope you guys get the basics of NodeJS, SocketIO and build yourself a simple real time app.

Tags: , , , , 

Thứ Ba, 1 tháng 2, 2022

NodeJS – Simple CRUD APIs with MySQL

In this article, I will do a simple CRUD APIs in NodeJS, Express and MySQL. We learn how to create restful (create, read, update, delete) api in NodeJS.

 

API End Points, test on Postman:

  • GET /learns: Give all learns stored in database
  • GET /learns/{id}: Give a specific user with id.
  • POST /learns : Create a record
  • PUT /learns/{id}: Update a record
  • DELETE /learns/{id}: Delete a record

 

Modules to install and use in this example:

  • express.js: Web framework express.
  • mysql: Node.js driver for MySQL.
  • body-parser: Converting the POST data into the request body.
  • nodemon: Automatically restart the server whenever the code changes.

 

1. Install the modules to use in NodeJS

Run [npm init] to initialize the source file, package.json. Select the js code file is index.js

npm init

Install these packages, type in the following command on Git Bash or your favorite cmd:

npm i –s express express-handlebars mysql body-parser

Installing nodemon with the global command:

npm i -g nodemon

 

We will have the following soure:

source-folder-method-get-list-nodejs-simple-crud-apis-with-mysql

Source folder

 

Package.json file content:

{
“name”: “nodemysql”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“body-parser”: “^1.19.0”,
“express”: “^4.17.1”,
“express-handlebars”: “^5.3.0”,
“mysql”: “^2.18.1”
}
}

 

2. MySQL Database

Create Database learns, with node_mysql_simple table as simple as follows:

// Schema: learns, DB: node_mysql_simple

CREATE DATABASE `learns` /*DEFAULT CHARACTER SET utf8 */;

CREATE TABLE `node_mysql_simple` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`course_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

database-method-get-list-nodejs-simple-crud-apis-with-mysql

MySQL Database

3. Index.js file server code

Use the required libraries that have been installed in NodeJS and establish a connection with MySQL.

const mysql = require(‘mysql’);
const express = require(‘express’);
const bodyparser = require(‘body-parser’);
var app = express();

// Express server
app.use(bodyparser.json());

// MySQL connection details
var mysqlConnection = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ”,
database: ‘learns’,
multipleStatements: true
});

mysqlConnection.connect((err) => {
if (!err) {
console.log(‘Connect success.’);
} else {
console.log(‘Connect faile: ‘ + JSON.stringify(err, undefined, 2));
}
});

const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listen on port ${port}…`));

 

Now you run the web server using command: node index.js

node index.js

And your server is running at port 8080.

gitbash-command-nodejs-simple-crud-apis-with-mysql

Command run the web server

 

3.1. Insert data to Database, method POST route

var urlencodedParser = bodyparser.urlencoded({ extended: false });

// Post route value get from params
app.post(‘/learns’, urlencodedParser, (req, res) => {
let name = req.body.name;
let email = req.body.email;
let course_id = req.body.course_id;

let sql = “INSERT INTO node_mysql_simple (name, email, course_id) VALUES (?, ?, ?)”;
mysqlConnection.query(sql, [name, email, course_id], (err, rows, fields) => {
if (!err) {
res.send(‘Inserted ID : ‘ + rows.insertId);
} else {
console.log(err);
}
})
});

 

– Test on Postman: Input simple data with name, email. course_id.

method-post-method-get-list-nodejs-simple-crud-apis-with-mysql

Method Post

 

Or you can use MySQL insert multiple rows from array.

// Post route direct value
app.post(‘/learnDirect’, (req, res) => {
// Multi values
let values = [
[‘Amit’, ‘amit@gmail’, 1],
[‘Rishi’, ‘rishi@gmail’, 1],
[‘Akash’, ‘akash@gmail’, 1],
];

let sql = ‘INSERT INTO node_mysql_simple (name, email, course_id) VALUES ?’;
mysqlConnection.query(sql, [values], (err, rows, fields) => {
if (!err) {
res.send(‘Inserted ID ‘ + rows.insertId);
} else {
console.log(‘Error: ‘ + err);
}
});
});

3.2. Show data list and detail data with method GET route

– Get route list:

// Get route list
app.get(‘/learns’, (req, res) => {
mysqlConnection.query(‘SELECT * FROM node_mysql_simple’, (err, rows, field) => {
if (!err) {
res.send(rows);
} else {
console.log(‘Query error: ‘ + err);
}
})
});

 

After inserting the second record, we have the results, test on Postman:

method-get-list-nodejs-simple-crud-apis-with-mysql

Method Get, get data list

 

– Get route detail:

// Get route detail
app.get(‘/learns/:id’, (req, res) => {
mysqlConnection.query(‘SELECT * FROM node_mysql_simple WHERE id = ?’, [req.params.id], (err, row, field) => {
if (!err) {
res.send(row);
} else {
console.log(‘Query error: ‘ + err);
}
})
});

 

method-get-detail-nodejs-simple-crud-apis-with-mysql

Method Get, get detail on Postman

 

3.3. Update data with method PUT route

// Put route value get from params
app.put(‘/learns/:id’, urlencodedParser, (req, res) => {
let id = req.params.id;

let name = req.body.name;
let email = req.body.email;
let course_id = req.body.course_id;

let sql = “UPDATE node_mysql_simple SET name = ?, email = ?, course_id = ? WHERE id = ?”;
mysqlConnection.query(sql, [name, email, course_id, id], (err, rows, fields) => {
if (!err) {
res.send(‘Updated with ID : ‘+ id);
} else {
console.log(err);
}
})
});

 

method-update-nodejs-simple-crud-apis-with-mysql

Method Update

 

3.4. Delete data with method Delete

// Route Delete
app.delete(‘/learns/:id’, (req, res) => {
mysqlConnection.query(‘DELETE FROM node_mysql_simple WHERE id = ?’, [req.params.id], (err, rows, fields) => {
if (!err) {
res.send(‘Delete success ID: ‘ + req.params.id);
} else {
console.log(‘Delete error: ‘ + err);
}
})
});

 

method-delete-nodejs-simple-crud-apis-with-mysql

Method Delete

 

– Maybe you are interested: PHP – MVC CRUD and Connect to MySQL using PDO

 

Thank for reading.

Thứ Ba, 25 tháng 1, 2022

Get Football ranking table with free API

 For sports fans it is common to follow the matches, update results, standings and player information. There are many websites, APIs that give us such data.

However, today I would like to introduce how to get the rankings, top football leagues by free api on apifootball.com, the results are shown below. Just get and display them on your website.

 

148-England-Premier-League

England-Premier-League (leagueId is 148)

 

We use Laravel with VueJS to do this.

1. Route:

The first is the route definition

// Route get rankings by tournament
Route::get(‘/standings/{leagueId}’, ‘Sport\FootballController@standings’);

// Route get team information in a tournament
Route::get(‘/teams/{leagueId}/{team_id}’, ‘Sport\FootballController@getTeams’);

// Route retrieves player details
Route::get(‘/players/{team_key}/{player_name}’, ‘Sport\FootballController@getPlayers’);

2. Controller

You need to register an API on the apifootball.com page, after having this API key, we use it to get data through the controller.

register-your-api-football

Your API

 

IDs of the tournaments (league_id), will be provided here: https://apifootball.com/coverage/

 

 

ids-of-the-tournaments

IDs of the tournaments (league_id)

 

The three functions in the controller have the following meanings:

– standings($leagueId): Ranking of a tournament.
– getTeams($league_id, $team_id): Team information in a tournament.
– getPlayers($team_key, $player_name): Details of players on the team.

 

In the FootballController file: App\Http\Controllers\Api\Sport

namespace App\Http\Controllers\Api\Sport;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FootballController extends Controller
{
private $api_key;

public function __construct($api_key = ‘YOUR_API_KEY’)
{
$this->api_key = $api_key;
}

public function standings($leagueId)
{
$APIkey = $this->api_key;
$curl_options = array(
CURLOPT_URL => “https://apiv2.apifootball.com/?action=get_standings&league_id=$leagueId&APIkey=$APIkey”,

CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 5
);

$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
$result = (array) json_decode($result);

return $result;
}

public function getTeams(Request $request, $league_id, $team_id)
{
// Because the code is quite long, I will put it in the download file at the bottom of the page
}

public function getPlayers(Request $request, $team_key, $player_name)
{
// Because the code is quite long, I will put it in the download file at the bottom of the page
}
}

 

3. VueJS

– In the app.js file: resource/js/app.js

require(‘./bootstrap’);

import Vue from ‘vue’;
import VueRouter from ‘vue-router’;

Vue.use(VueRouter);

import App from ‘./views/App’

// Fooball
import Standing from ‘./components/Football/StandingTable’;
import GetTeams from ‘./components/Football/GetTeams’;
import GetPlayers from ‘./components/Football/GetPlayers’;

const router = new VueRouter({
mode: ‘history’,
routes: [
{
path: ‘/’,
name: ‘home’,
component: Home
},
{
path: ‘/standings/:leagueId’,
name: ‘fb.standing’,
component: Standing
},
{
path: ‘/teams/:leagueId/:team_id’,
name: ‘fb.getTeams’,
component: GetTeams
},
{
path: ‘/players/:team_key/:player_name’,
name: ‘fb.getPlayers’,
component: GetPlayers
},

// …
],

});

const app = new Vue({
el: ‘#app’,
components: { App, Datepicker },
router,
});

– In the StandingTable.vue file: resource/js/components/Football/StandingTable.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

– In the GetTeams file: resource/js/components/Football/GetTeams.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

– In the GetPlayers file: resource/js/components/Football/GetPlayers.vue
// Because the code is quite long, I will put it in the download file at the bottom of the page

First I assume you pass leagueId = 148 (England – Premier League) which will be as shown above.

With leagueId = 468 (LaLiga), we will see the following.

 

468-LaLiga

LaLiga (leagueId id 468)

 

– Click View Detail to view detailed information.

 

barcenola-team-detail

Barcenola team detail

 

Reference links: https://popularinfo.net/standings/148

Wish you success with this free API, Laravel and VueJS thanks for reading the article.

 

Download full code: Download Size: 6 KB


Chủ Nhật, 23 tháng 1, 2022

Frontend form validation with VueJS

Hello everyone, in all forms such as login, registration or checking information, etc. In Frontend we need to validate the data for it before it is processed in the backend and saved to the Database.

Checking data in Frontend form using VueJS is a way to greatly reduce time compared to when you check data in the backend.

In this example, we will validation the data of the most basic components, which are required to enter textbox, email, number and value of total number.

 

frontend-form-validation-with VueJS

Frontend form validation with VueJS

 

1. VueJS and Bootstrap

If you have not installed VueJS and bootstrap, please call the library as below:

<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js”></script>

<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css”>

 

2. The HTML form tags are as follows:

– error: Displayed if there are errors.length > 0

– How to declare v-model can be used one of two ways (for example at position Number 1)

     <div class=”container”>
<h1>Validation form with VueJS</h1>
<form action=”/” method=”POST” @submit=”checkForm” novalidate=”true” id=”app”>
<div v-if=”errors.length”>
<p><b>Please correct the following errors: </b></p>
<div class=”flash-message” v-for=”error in errors”>
<p class=”alert alert-danger”>{{ error }}</p>
</div>
</div>
<div class=”form-group”>
<div class=”row”>
<label for=”name” class=”col-md-2 text-right”>Name:</label>
<input type=”text” name=”name” v-model=”name” class=”form-control col-md-5″ />
</div>
</div>
<div class=”form-group”>
<div class=”row”>
<label for=”email” class=”col-md-2 text-right”>Email</label>
<input type=”email” name=”email” v-model=”email” class=”form-control col-md-5″ />
</div>
</div>
<div class=”form-group”>
<div class=”row”>
<label for=”number1″ class=”col-md-2 text-right”>Number 1</label>
<!– <input type=”number” v-model=”number1″ min=”0″/> v-model or v-model.number –>
<input type=”number” v-model.number=”number1″ min=”0″ class=”form-control col-md-5″ />
</div>
</div>
<div class=”form-group”>
<div class=”row”>
<label for=”number2″ class=”col-md-2 text-right”>Number 2</label>
<input type=”number” v-model=”number2″ min=”0″ class=”form-control col-md-5″ />
</div>
</div>
<div class=”form-group”>
<div class=”row”>
<div class=”col-md-2 text-right”>
<button type=”submit” class=”btn btn-primary”>Submit</button>
</div>
</div>
</div>
</form>
</div>

 

3. Script to handle validate

– el: ‘app’ is the form submit ID

– total: The processing function calculates the sum

– checkForm: The checkForm function executes before the form is submitted

– validEmail: Check that the entered value is in the correct email format

 

const app = new Vue({
el: ‘#app’,
data: {
errors: [],
name: null,
email: null,
number1: null,
number2: null
},
computed: {
total: function() {
return Number(this.number1) + Number(this.number2);
}
},
methods: {
checkForm: function(e) {
this.errors = [];
if (!this.name) {
this.errors.push(‘Name required.’);
}
if (!this.email) {
this.errors.push(‘Email is required.’);
} else if (!this.validEmail(this.email)) {
this.errors.push(‘Email is not validate’);
}
if (this.number < 0) {
this.errors.push(‘Number must unsinged’);
}
if (this.total != 20) {
this.errors.push(‘Total number must be 20’);
}
if (!this.errors.length) return true;
e.preventDefault();

},
validEmail:function(email) {
var re = /^(([^<>()\[\]\\.,;:\s@”]+(\.[^<>()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
});

Thứ Tư, 19 tháng 1, 2022

Simple example for VueJS Search Filter

Search is an extremely important component in every website that contains many categories and components. Especially the site about e-commerce, blog, news, etc. All need the search function to select information.

This article applies to the quick search of data in the array that is returned as soon as you enter your search keywords, below I have written how to call the API that returns the datas array and assuming an array datas is available.

 

simple-example-for-vueis-search-filter

Simple example for VueJS Search Filter

 

First, we assume that there is an API that returns data, including post title and article category name:

datas: [
{ title:”Add weather and time zone information to your website from free API”, category:”VueJS” },
{ title:”How to import data from excel file, csv into the database and export back”, category:”PHP-MySQL” },
{ title:”PHP – MVC CRUD and Connect to MySQL using PDO”, category:”PHP-MySQL” },
{ title:”Automatically backup MySQL database with Batch file on Windows”, category:”PHP-MySQL” },
{ title:”Add and Remove input textbox with Jquery, Javascript”, category:”Jquery-Javascript” },
{ title:”Customizable multi-type, multi-y axis code ChartJS – Part 2″, category:”Jquery-Javascript” },
{ title:”Customizable multi-type, multi-y axis code ChartJS – Part 1″, category:”Jquery-Javascript” },
];

 

If you have VueJS installed, that’s great, but just want to test quickly without installation, add the VueJS library as below, and add Bootstrap to use it.

<script src=”https://cdn.jsdelivr.net/npm/vue@2.6.12″></script>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css”>

About template.vue

– You need an input box to enter the keyword search, a loading icon shows the time it takes to show dataư

– resultQuery: If there is datas, the data will be retrieved in the for loop

<template>
<div class=”col-md-12 text-center”>
<div class=”col-md-4 p-0″>
<input type=”text” v-model=”quickSearch” placeholder=”Quick search…” class=”form-control”>
</div>
<p v-if=”loading” class=”text-center”><img :src=”‘https://softdownloadfree.com/uploads/images/loading-icon.gif'” alt=”loading” width=”35px”/></p>

<div class=”text-left” v-if=”resultQuery”>
<div class=”col-md-12 mb-1″ style=”display:inline-block” v-for=”item in resultQuery”>
<h3 v-if=”item.title”>{{ item.title }}</h3>
</div>
</div>
</div>
</template>

 

About resultQuery data processing:

– If you have not entered the search keyword, the data will display all the values in the datas array which were retrieved (return this.datas).

– When entering search keywords, you can search only by title or multiple arguments (VueJS search filter multiple arguments). Below is the search by title and category, and is not case sensitive.

<script type=”text/javascript”>
export default {
data () {
return {
error: null,
loading: true,
datas: [
{ title:”Add weather and time zone information to your website from free API”, category:”VueJS” },
{ title:”How to import data from excel file, csv into the database and export back”, category:”PHP-MySQL” },
{ title:”PHP – MVC CRUD and Connect to MySQL using PDO”, category:”PHP-MySQL” },
{ title:”Automatically backup MySQL database with Batch file on Windows”, category:”PHP-MySQL” },
{ title:”Add and Remove input textbox with Jquery, Javascript”, category:”Jquery-Javascript” },
{ title:”Customizable multi-type, multi-y axis code ChartJS – Part 2″, category:”Jquery-Javascript” },
{ title:”Customizable multi-type, multi-y axis code ChartJS – Part 1″, category:”Jquery-Javascript” },
];
quickSearch: null,
}
},
computed: {
resultQuery() {
if (this.quickSearch) {
return this.datas.filter((item)=>{
return this.quickSearch.toLowerCase().split(‘ ‘).every(v => item.title.toLowerCase().includes(v) || item.category.toLowerCase().includes(v))
})
} else {
return this.datas;
}
},
}
}
</script>

 

At this point, we have completed the simple vuejs search filter with the given data.

 

If you get the data returned by the API, you should use axios to do this.

The beforeRouteEnter and beforeRouteUpdate functions are used to load the priority data as soon as the page is loaded.

<script type=”text/javascript”>
import axios from ‘axios’;
const getData = (page, callback) => {
const params = { page };
axios
.get(‘/api/post’, { params })
.then(response => {
callback(null, response.data);
})
.catch(error => {
callback(error, response);
});
};

export default {
data () {
return {
error: null,
loading: true,
datas: null,
quickSearch: null,
}
},
computed: {
resultQuery() {
if (this.quickSearch) {
return this.datas.filter((item)=>{
return this.quickSearch.toLowerCase().split(‘ ‘).every(v => item.title.toLowerCase().includes(v) || item.category.toLowerCase().includes(v))
})
} else {
return this.datas;
}
},
beforeRouteEnter(to, from, next) {
getData(to.query.page, (err, results) => {
next(vm => vm.setData(err, results));
})
},
beforeRouteUpdate(to, from, next) {
this.loading = true;
this.results = null;
getData(to.query.page, (err, results) => {
this.setData(err, results);
next();
})
},
methods: {
setData(err, {results}) {
this.loading = true;
if (err) {
this.err = err.toString();
} else {
this.loading = false;
this.datas = results;
}
},
}
}
}
</script>

 

So we have completed the quick search function with multiple parameters using VueJS

You can refer to the results at the home page: https://softdownloadfree.com or site category page https://softdownloadfree.com/category/vuejs/

 

Thank you for reading the article.