Search

VueJs's Articles

Vue.js is an open-source Model–view–viewmodel JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members coming from various companies such as Netlify and Netguru.

Create a Chart using chartJs in VueJs
This tutorial expounds about how to engender awe-inspiring charts that will avail us to understand the data or information in meaning full ways. I will show you how to engender pulchritudinous charts in Vue.js 2+ app utilizing Chart.js and vue-chartjs plugin. Data visualization is a consequential aspect nowadays, and Charts are the best implements to represent the information for everybody. Charts process our encephalons to understand the data more facilely and expeditiously than the textual information. The most critical information can be facilely scanned with the avail of Charts, which is not possible in a textual form of data. Vue.js is a lenient JavaScript framework to engender utilizable utilizer-interfaces. We will take the avail of Chart.js and vue-chartjs to manifest the chart examples. So, Let’s get commenced. Install Vue Project with Vue CLI First, we have to install the Vue CLI using given below command: npm install -g @vue/cli Next, we can install the Vue project: vue create vue-chart-js-app Vue CLI asks following question: # ? Please pick a preset: Manually select features # ? Check the features needed for your project: Babel, Router, CSS Pre-processors, Linter # ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes # ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) # ? Pick a linter / formatter config: Basic # ? Pick additional lint features: Lint on save # ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json # ? Save this as a preset for future projects? (y/N) No Get inside the project: cd vue-chart-js-app Let’s start the project and check in the browser: npm run serve Install Chart.js and vue-chartjs Plugins Run the command to install vue-chartjs and Chart.js plugins. # npm npm install vue-chartjs chart.js --save # yarn yarn add vue-chartjs chart.js Chart.js is a powerful, straightforward, yet flexible open-source JavaScript library for software developers. It helps in creating various stunning charts using HTML5 canvas. It is a well-known library, and you can figure out the popularity of this library by seeing more than 48.1k+ stars on GitHub. You can draw the following charts with Chart.js: Line Bar Doughnut Pie Radar Polar Area Bubble Scatter The vue-chartjs provides a wrapper for Chart.js in Vue. It allows creating reusable chart components to display useful information that can be easily understood graphically. This plugin is highly compatible with Vue.js 2.x +. Creating & Setting Up Charts Components In this step, we will create components and views for the charts examples. Create the given below files inside the src/views folder: Line.vue => (Home.vue) Bar.vue Doughnut.vue Pie.vue Radar.vue PolarArea.vue Bubble.vue Scatter.vue Next, create the given below src/components folder: LineChart.vue BarChart.vue DoughnutChart.vue PieChart.vue RadarChart.vue PolarAreaChart.vue BubbleChart.vue ScatterChart.vue Create & Set up Routes in Vue Now, we need to create and configure the routes in our Vue app. These routes will allow us to display the charts from the component we generated above. Open router/index.js file and replace the existing code with the following code. import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/bar', name: 'Bar', component: () => import('../views/Bar.vue') }, { path: '/doughnut', name: 'Doughnut', component: () => import('../views/Doughnut.vue') }, { path: '/pie', name: 'Pie', component: () => import('../views/Pie.vue') }, { path: '/radar', name: 'Radar', component: () => import('../views/Radar.vue') }, { path: '/polar-area', name: 'PolarArea', component: () => import('../views/PolarArea.vue') }, { path: '/bubble', name: 'Bubble', component: () => import('../views/Bubble.vue') }, { path: '/scatter', name: 'Scatter', component: () => import('../views/Scatter.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router Open src/App.vue and replace the current code with the given blow code. <template> <div id="app"> <div id="nav"> <router-link to="/">Line</router-link> | <router-link to="/bar">Bar</router-link> | <router-link to="/doughnut">Doughnut</router-link> | <router-link to="/pie">Pie</router-link> | <router-link to="/radar">Radar</router-link> | <router-link to="/polar-area">Polar Area</router-link> | <router-link to="/bubble">Bubble</router-link> | <router-link to="/scatter">Scatter</router-link> </div> <div class="container"> <div class="row"> <div class="col-12"> <router-view /> </div> </div> </div> </div> </template> <style lang="scss"> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px 30px 60px; a { font-weight: bold; color: #2c3e50; &.router-link-exact-active { color: #42b983; } } } </style> We enabled the navigation in Vue by defining the router-link inside the src/App.vue file. The <router-view /> directive will display the associated view for the particular Chart component. Vue Line Chart Example Now, we will create a line chart. Go to components/LineChart.vue and place the following code. <script> import { Line } from 'vue-chartjs' export default { extends: Line, data () { return { chartData: { labels: ["Babol", "Cabanatuan", "Daegu", "Jerusalem", "Fairfield", "New York", "Gangtok", "Buenos Aires", "Hafar Al-Batin", "Idlib"], datasets: [ { label: 'Line Chart', data: [600, 1150, 342, 6050, 2522, 3241, 1259, 157, 1545, 9841], fill: false, borderColor: '#2554FF', backgroundColor: '#2554FF', borderWidth: 1 } ] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: true } }], xAxes: [ { gridLines: { display: false } }] }, legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted () { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/Home.vue. Here, we will display the Line chart, so add the line-chart tag and import the LineChart component inside the view. <template> <div> <h3>Line Chart Example in Vue</h3> <line-chart></line-chart> </div> </template> <script> import LineChart from '@/components/LineChart' export default { components: { LineChart } } </script> Bar Chart Example in Vue To create a Bar chart, open components/BarChart.vue file and place the following code. <script> import { Bar } from 'vue-chartjs' export default { extends: Bar, data() { return { chartData: { labels: ["2015-01", "2015-02", "2015-03", "2015-04", "2015-05", "2015-06", "2015-07", "2015-08", "2015-09", "2015-10", "2015-11", "2015-12" ], datasets: [{ label: 'Bar Chart', borderWidth: 1, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], pointBorderColor: '#2554FF', data: [12, 19, 3, 5, 2, 3, 20, 3, 5, 6, 2, 1] }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: true } }], xAxes: [{ gridLines: { display: false } }] }, legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted() { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/Bar.vue file. Here, we have to show the Bar chart, so add the bar-chart tag inside the template directive and import the BarChart component in the view. <template> <div> <h3>Bar Chart Example in Vue</h3> <bar-chart></bar-chart> </div> </template> <script> import BarChart from '@/components/BarChart' export default { components: { BarChart } } </script> Vue Doughnut Chart Example To create a Doughnut chart, open components/DoughnutChart.vue file and add the following code. <script> import { Doughnut } from 'vue-chartjs' export default { extends: Doughnut, data () { return { chartData: { labels: ["Babol", "Cabanatuan", "Daegu", "Jerusalem"], datasets: [{ borderWidth: 1, borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)' ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', ], data: [1000, 500, 1500, 1000] }] }, options: { legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted () { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/Doughnut.vue file. Here, we have to show the Doughnut chart, so add the doughnut-chart tag inside the template directive and import the DoughnutChart component in the view. <template> <div> <h3>Doughnut Chart Example in Vue</h3> <doughnut-chart></doughnut-chart> </div> </template> <script> import DoughnutChart from '@/components/DoughnutChart' export default { components: { DoughnutChart } } </script> Pie Chart Example in Vue To create a Pie chart, open components/PieChart.vue file and add the following code. <script> import { Pie } from 'vue-chartjs' export default { extends: Pie, data () { return { chartData: { labels: ["Italy", "India", "Japan", "USA",], datasets: [{ borderWidth: 1, borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)' ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', ], data: [1000, 500, 1500, 1000] }] }, options: { legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted () { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/Pie.vue file. Here, we have to show the Pie chart, so add the pie-chart tag inside the template directive and import the PieChart component in the view. <template> <div> <h3>Pie Chart Example in Vue</h3> <pie-chart></pie-chart> </div> </template> <script> import PieChart from '@/components/PieChart' export default { components: { PieChart } } </script> Radar Chart Example To create a Radar chart, open components/RadarChart.vue file and add the following code. <script> import { Radar } from 'vue-chartjs' export default { extends: Radar, data () { return { chartData: { labels: [ "Babol", "Cabanatuan", "Daegu", "Jerusalem", "Fairfield", "New York", "Gangtok", "Buenos Aires", "Hafar Al-Batin", "Idlib" ], datasets: [ { label: 'Radar Chart', borderWidth: 1, backgroundColor: 'rgba(54, 162, 235, 0.2)', data: [ 32127289, 24724027, 25820412, 23685667, 25644258, 22433220, 22966210, 22743184, 21880515, 21543111 ] } ] }, options: { responsive: true, maintainAspectRatio: false } } }, mounted () { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/Radar.vue file. Here, we have to show the Radar chart, so add the radar-chart tag inside the template directive and import the RadarChart component in the view. <template> <div> <h3>Radar Chart Example in Vue</h3> <radar-chart></radar-chart> </div> </template> <script> import RadarChart from '@/components/RadarChart' export default { components: { RadarChart } } </script> Polar Area Chart Example To create a Polar Area chart, open components/PolarAreaChart.vue file and add the following code. <script> import { PolarArea } from 'vue-chartjs' export default { extends: PolarArea, data () { return { chartData: { labels: ['Pink', 'Blue', 'Yellow', 'Green', 'Purple'], datasets: [ { label: 'Polar Area Chart', borderWidth: 1, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', ], data: [8, 14, 12, 7, 20] } ] }, options: { responsive: true, maintainAspectRatio: false } } }, mounted () { this.renderChart(this.chartData, this.options) } } </script> Next, open the views/PolarArea.vue file. Here, we have to show the PolarArea chart, so add the polar-area-chart tag inside the template directive and import the PolarAreaChart component in the view. <template> <div> <h3>Polar Area Chart Example in Vue</h3> <polar-area-chart></polar-area-chart> </div> </template> <script> import PolarAreaChart from '@/components/PolarAreaChart' export default { components: { PolarAreaChart } } </script> Bubble Chart Example In this step we will create Bubble Area chart, so open the components/BubbleChart.vue file and add the given below code. <script> import { Bubble } from 'vue-chartjs' export default { extends: Bubble, data() { return { chartData: { datasets: [{ label: 'Population Data', borderWidth: 1, borderColor: '#2554FF', backgroundColor: '#2554FF', data: [{ x: 6, y: 3, r: 15 }, { x: 3, y: 12, r: 4 }, { x: 5, y: 15, r: 10 }, { x: 3, y: 12, r: 8 }, { x: 4, y: 5, r: 20 }, { x: 2, y: 6, r: 3 }, { x: 4, y: 9, r: 11 }, { x: 5, y: 10, r: 6 } ] }] }, options: { legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted() { this.renderChart(this.chartData, this.options) } } </script> Then, go to views/Bubble.vue file. Here, we need to display the Bubble chart, so add the bubble-chart tag inside the vue’s template directive and import the BubbleChart component in the view. <template> <div> <h3>Bubble Chart Example in Vue</h3> <bubble-chart></bubble-chart> </div> </template> <script> import BubbleChart from '@/components/BubbleChart' export default { components: { BubbleChart } } </script> Scatter Chart Example In this step we will create Bubble Area chart, so open the components/ScatterChart.vue file and add the given below code. <script> import { Scatter } from 'vue-chartjs' export default { extends: Scatter, data() { return { chartData: { datasets: [{ label: 'Population Data', borderWidth: 1, borderColor: '#2554FF', backgroundColor: '#2554FF', data: [{ x: 6, y: 3, r: 15 }, { x: 3, y: 12, r: 4 }, { x: 5, y: 15, r: 10 }, { x: 3, y: 12, r: 8 }, { x: 4, y: 5, r: 20 }, { x: 2, y: 6, r: 3 }, { x: 4, y: 9, r: 11 }, { x: 5, y: 10, r: 6 } ] }] }, options: { legend: { display: true }, responsive: true, maintainAspectRatio: false } } }, mounted() { this.renderChart(this.chartData, this.options) } } </script> Then, go to views/Scatter.vue file. Here, we need to display the Scatter chart, so add the scatter-chart tag inside the vue’s template directive and import the ScatterChart component in the view. <template> <div> <h3>Scatter Chart Example in Vue</h3> <scatter-chart></scatter-chart> </div> </template> <script> import ScatterChart from '@/components/ScatterChart' export default { components: { ScatterChart } } </script> i hope you like this article.
Single and Multiple Files Upload in VueJs
In this tutorial, we are going to learn how to upload single & multiple files and images to the Node server from Vue.js application utilizing Express.js API. Along with that, we will withal learn how to send multipart form data utilizing FormData() web API. Let’s get commenced. Set Up Project Use command to install Vue project: vue create vue-single-multi-files-upload Enter inside the project: cd vue-single-multi-files-upload Start the app in the browser: npm run serve Configure Bootstrap Open the public/index.html file and add the Bootstrap CDN link. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"> Install Axios Library Install Axios library in Vue.js app to make the API requests. # NPM npm install axios --save # Yarn yarn add axios Build Express/Node Server We will be uploading files and images in the remote server so that we will create a backend server using Node. Create file upload API using Express.js and store it in the MongoDB database. Create a server folder at the root of your Vue.js project. mkdir server && cd server Create package.json for node server. npm init We need to install the following dependencies. npm i --save cors express mongoose multer body-parser We have to install the nodemon package to re-start the node server. Define MongoDB Database Create server/db/database.js file and folder, here we will define the mongoDB database. module.exports = { db: 'mongodb://localhost:27017/fileupload' } Create Schema Create server/models folder, create a new file and name it User.js. const mongoose = require('mongoose'); const Schema = mongoose.Schema; let userSchema = new Schema({ _id: mongoose.Schema.Types.ObjectId, files: { type: Array }, }, { collection: 'users' }) module.exports = mongoose.model('User', userSchema) Create File Upload API Create a new folder server/public, and we are going to store uploaded files in this folder. mkdir public Next, we need to create a server/routes folder; in this folder, we have to create user.routes.js file. Add all the following code inside the routes file. let express = require('express'), multer = require('multer'), mongoose = require('mongoose'), router = express.Router(); const DIR = './public/'; const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, DIR); }, filename: (req, file, cb) => { const fileName = file.originalname.toLowerCase().split(' ').join('-'); cb(null, fileName) } }); var upload = multer({ storage: storage, fileFilter: (req, file, cb) => { if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") { cb(null, true); } else { cb(null, false); return cb(new Error('Only .png, .jpg and .jpeg format allowed!')); } } }); // User model let User = require('../models/User'); router.post('/file-upload', upload.array('files', 10), (req, res, next) => { const reqFiles = [] const url = req.protocol + '://' + req.get('host') for (var i = 0; i < req.files.length; i++) { reqFiles.push(url + '/public/' + req.files[i].filename) } const user = new User({ _id: new mongoose.Types.ObjectId(), files: reqFiles }); user.save().then(result => { console.log(result); res.status(201).json({ message: "Done upload!", userCreated: { _id: result._id, files: result.files } }) }).catch(err => { console.log(err), res.status(500).json({ error: err }); }) }) router.get("/", (req, res, next) => { User.find().then(data => { res.status(200).json({ message: "Data fetched!", users: data }); }); }); module.exports = router; The Multer package provides the upload.array method. This method takes two parameters, the file name and the total number of files to be uploaded to the server. You can have a look at the full Multer documentation here. Set up Node Server Next, we need to create a server/index.js file. In this file, we define all the server related settings. let express = require('express'), mongoose = require('mongoose'), cors = require('cors'), bodyParser = require('body-parser'), dbConfig = require('./db/database'); // Routes to Handle Request const userRoute = require('../server/routes/user.routes') // MongoDB Setup mongoose.Promise = global.Promise; mongoose.connect(dbConfig.db, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Database sucessfully connected') }, error => { console.log('Database could not be connected: ' + error) } ) // Setup Express.js const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cors()); // Make Images "Uploads" Folder Publicly Available app.use('/public', express.static('public')); // API Route app.use('/api', userRoute) const port = process.env.PORT || 4000; const server = app.listen(port, () => { console.log('Connected to port ' + port) }) // Error app.use((req, res, next) => { // Error goes via `next()` method setImmediate(() => { next(new Error('Something went wrong')); }); }); app.use(function (err, req, res, next) { console.error(err.message); if (!err.statusCode) err.statusCode = 500; res.status(err.statusCode).send(err.message); }); Run the Express Server Open the terminal window and run the following command to start the MongoDB database. mongod --config /usr/local/etc/mongod.conf brew services start mongodb-community@4.2 mongo Start the nodemon server: nodemon index.js Here are the file upload API we created: We have created the File Uploading API using Node and Express.js. Now let us test out our newly built API using Postmen. Method API GET http://localhost:4000/api POST http://localhost:4000/api/file-upload Create Single & Multiple Files Uploading Component In this step we will build Single & Multiple Files and Images Uploading component. First, create a component/fileUpload.vue in Vue app. Then, add the following code inside of it. <template> <div> <div class="container"> <form @submit.prevent="handleSubmit"> <div class="form-group"> <input type="file" @change="uploadFile" multiple> </div> <div class="form-group"> <button class="btn btn-success btn-block btn-lg">Upload</button> </div> </form> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { files: null }; }, methods: { uploadFile (event) { this.files = event.target.files }, handleSubmit() { const formData = new FormData(); for (const i of Object.keys(this.files)) { formData.append('files', this.files[i]) } axios.post('http://localhost:4000/api/file-upload', formData, { }).then((res) => { console.log(res) }) } } } </script> <style scoped lang="scss"> .container { max-width: 600px; } </style>   The axios.post() method takes the file uploading API that we created using Express.js; the second parameter is the form data that we are sending to the server in multi-parts. The Object.keys() method returns an array of a given object’s enumerable property names, here we are extracting the files from the FileList API by iterating in the same order that a standard loop does. Summary So this was it, in this tutorial, we have learned how to upload files to the express server using Axios and FormData() web API. I hope you loved this articles. Don’t forget to share it with others. You can download the complete code of this tutorial here.  
Show Image Preview Before Upload in VueJs
If you optate to show image preview afore it gets uploaded to the server in Vue.js than you are at the right place. If you are a neophyte in Vue application development, then you must check out our anteriorly indited tutorials on image uploading. Upload Single & Multiple Images in Vue with Node & Express. A utilizer always wants to optically discern a preview of the image afore he wants to upload or send it to the webserver. Image preview is a process in which a utilizer views a preview of his uploaded image. If you don’t provide this feature in your web and mobile application, it leads a utilizer to a negative utilizer experience. A utilizer considers your app to be less efficacious in terms of usability. In this tutorial, we are going to engender a custom image preview feature in a vue application. However, there are plenty of plugins available that can sanction you to handle image preview in vue within minutes. Initializing Vue Project Let’s set up the environment by setting up a basic vue project. We need to install the vue project using vue CLI, run the following command. vue create vue-image-preview Get inside the project: cd vue-image-preview Start the vue project: npm run serve Create Image Preview Component Now, we have to create components/filePreview.vue file. In this component, we will be writing code that will show us the instant image preview in vue. Open the filePreview.vue file and add the vue template in it. In the vue template, we defined the HTML tags: The imagePreviewWrapper div will receive the image link, and image will be added as a background image via the previewImage data variable. The selectImage property corresponds to the click event. A user will communicate with <input type="file">. This will work as a file picker, and we will choose a file and process the image using the FileReader API. <template> <div> <div class="imagePreviewWrapper" :style="{ 'background-image': `url(${previewImage})` }" @click="selectImage"> </div> <input ref="fileInput" type="file" @input="pickFile"> </div> </template> Next, add the following code in the filePreview.vue component. <script> export default { data() { return { previewImage: null }; }, methods: { selectImage () { this.$refs.fileInput.click() }, pickFile () { let input = this.$refs.fileInput let file = input.files if (file && file[0]) { let reader = new FileReader reader.onload = e => { this.previewImage = e.target.result } reader.readAsDataURL(file[0]) this.$emit('input', file[0]) } } } } </script> The previewImage holds the image data or preview url. The pickFile method triggers when the user selects the image using file input. Inside the pickFile() function, we are taking the help of FileReader web API, and This API will help us choosing the file and convert it to DataURL using the readAsDataURL method. We will add the base64 data as a background image url to show the image preview. However, we are not going to store the base64 URL on the server. Finally, we need to add the little bit of style for the image preview block at the bottom of the vue component: <style scoped lang="scss"> .imagePreviewWrapper { width: 250px; height: 250px; display: block; cursor: pointer; margin: 0 auto 30px; background-size: cover; background-position: center center; } </style> Here is the final code that directly goes to filePreview.vue component. <template> <div> <div class="imagePreviewWrapper" :style="{ 'background-image': `url(${previewImage})` }" @click="selectImage"> </div> <input ref="fileInput" type="file" @input="pickFile"> </div> </template> <script> export default { data() { return { previewImage: null }; }, methods: { selectImage () { this.$refs.fileInput.click() }, pickFile () { let input = this.$refs.fileInput let file = input.files if (file && file[0]) { let reader = new FileReader reader.onload = e => { this.previewImage = e.target.result } reader.readAsDataURL(file[0]) this.$emit('input', file[0]) } } } } </script> <style scoped lang="scss"> .imagePreviewWrapper { width: 250px; height: 250px; display: block; cursor: pointer; margin: 0 auto 30px; background-size: cover; background-position: center center; } </style> i hope you like this article.
VueJs CRUD using Google Firebase
This is a step by step tutorial that explicates how to build a Vue.js 2+ CRUD web application utilizing Firebase database. We are going to engender a rudimental customer records management system, in which a utilizer can perform CRUD operations and store the data into the Cloud Firestore. Firebase abbreviates the pain of maintaining the backend server because Firebase is Backend-as-a-accommodation. It gives liberation to developers to fixate on enhancing the utilizer experiences rather than maintaining the backend or server. It updates the data in authentic-time even it updates the data on all the connected contrivances as anon as the information updates on the cloud Firestore, and the resplendent thing is you don’t have to indite the APIs. Here are some of the Firebase Features: Push notifications Ready-made API Realtime data update Enhanced security Cloud storage Easy A/B testing Analytics monitoring Easy server management Offline access to WEB SDK Hosting and cloud storage Authentication with Email & password, Google, Facebook, & Github Vue.js Firebase CRUD Web App Example We require following tools and frameworks: Vue CLI v4.3.1 Vue 2.6.11 Firebase Bootstrap 4 IDE or Code Editor Setting up Firebase Project We need firebase configuration details to connect Firebase with the Vue.js app. So, in this step, we will create a Firebase project inside the Firebase dashboard. Click “Create a project”. Click on “Add project”, we don’t need to enable analytics for this demo. Click on “Continue” to generate the project. Click on the web icon. Provide the app nickname and click on “Next”. Copy Firebase configuration details, It connects Vue with Firebase. Click on “Database” => “Cloud Firestore” and click on the “Create Database”. Configure the security rules in test mode. Next, create a “users” collection. You can make as many collection as you want. The collection is a set of document that contains specific information or data. Create Vue App with Vue CLI The Vue CLI offers the conventional tooling for rapid Vue.js development. Run the command in the terminal to install Vue CLI. npm install -g @vue/cli # or yarn global add @vue/cli Verify the vue-cli installed version: vue --version Create a brand new Vue.js project from scratch using the below command. vue create vue-firebase-crud-app Answer the following question asked by Vue CLI: # ? Please pick a preset: Manually select features # ? Check the features needed for your project: Babel, Router, CSS Pre-processors, Linter # ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes # ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with dart-sass) # ? Pick a linter / formatter config: Basic # ? Pick additional lint features: Lint on save # ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json # ? Save this as a preset for future projects? (y/N) No Head over to the newly installed project folder. cd vue-firebase-crud-app Run the command to see the vue app on the browser. npm run serve App can be seen at: Local: http://localhost:8080/ Network: http://192.168.0.103:8080/ Add Bootstrap 4 in Vue Open the terminal and run the command to install Bootstrap in Vue. npm install bootstrap # or yarn add bootstrap Add the Import path in the main.js file. It will let us use the Bootstrap components throughout the vue application. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Creating Vue Components To manage the data or our CRUD application, we need to create the following files inside the “components” folder. UserCreate.vue UserEdit.vue UserList.vue A regular vue component seems like this: <template> <div class="row justify-content-center"> <div class="col-md-6"> <!-- Content goes here --> </div> </div> </template> <script> export default { data() { return { } } } </script> </div> Create Vue Router for Firebase CRUD Demo App Go to router/index.js file and replace with the given code. We are adding the particular url path with its associated component. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'add', component: () => import('../components/UserCreate') }, { path: '/list', name: 'list', component: () => import('../components/UserList') }, { path: '/edit/:id', name: 'edit', component: () => import('../components/UserEdit') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router Add Navigation with Router View The Bootstrap navigation component creates the beautiful header with nav items. The router-link directive navigates to the specific page, and the router-view directive displays the associated component with its router. Open src/App.vue file, add the following code in it. <template> <div> <nav class="navbar navbar-dark bg-dark justify-content-between flex-nowrap flex-row"> <div class="container"> <a class="navbar-brand float-left">Firebase Vue CRUD Example</a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/">Add User</router-link> </li> <li class="nav-item"> <router-link class="nav-link" to="/list">View Users</router-link> </li> </ul> </div> </nav> <div class="container mt-5"> <router-view></router-view> </div> </div> </template> Create Interactive Vue Form with Bootstrap Add the following code inside components/UserCreate.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Add User</h3> <form @submit.prevent="onFormSubmit"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> export default { data() { return { user: { name: '', email: '', phone: '' } } }, methods: { onFormSubmit() { alert(JSON.stringify(this.user)) } } } </script> Install and Set up Firebase in Vue Install Firebase plugin in vue.js, it makes the communication between Vue and Cloud Firestore. npm install firebase Create a src/firebaseDb.js file then add the following code to establish the real-time database connection in vue with your Firebase configurations details. import * as firebase from 'firebase'; const firebaseConfig = { apiKey: "api-key", authDomain: "project-id.firebaseapp.com", databaseURL: "https://project-id.firebaseio.com", projectId: "project-id", storageBucket: "project-id.appspot.com", messagingSenderId: "sender-id", appId: "app-id", measurementId: "G-measurement-id" } const firebaseApp = firebase.initializeApp(firebaseConfig); export const db = firebaseApp.firestore(); Add Data in Cloud Firestore We will use the firestore collection() method to add the Data in the Cloud Firestore Database. Add the following code inside the UserCreate.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Add User</h3> <form @submit.prevent="onFormSubmit"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { user: { } } }, methods: { onFormSubmit(event) { event.preventDefault() db.collection('users').add(this.user).then(() => { alert("User successfully created!"); this.user.name = '' this.user.email = '' this.user.phone = '' }).catch((error) => { console.log(error); }); } } } </script> Display Data & Delete Data Object from Firestore The Bootstrap Table components is famously employed for representing the user data that we fetched from the Cloud Firestore using the collection(‘users’).get() method. The router-link directive is taking us to the user details page, and we passed the user key/id in the router link. To delete the user data object from Firestore, we passed the data key to the deleteUser(key) method. The data object can be removed using the delete() method. Add the following code inside the UserList.vue file. <template> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="user in Users" :key="user.key"> <td>{{ user.name }}</td> <td>{{ user.email }}</td> <td>{{ user.phone }}</td> <td> <router-link :to="{name: 'edit', params: { id: user.key }}" class="btn btn-primary">Edit </router-link> <button @click.prevent="deleteUser(user.key)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { Users: [] } }, created() { db.collection('users').onSnapshot((snapshotChange) => { this.Users = []; snapshotChange.forEach((doc) => { this.Users.push({ key: doc.id, name: doc.data().name, email: doc.data().email, phone: doc.data().phone }) }); }) }, methods: { deleteUser(id){ if (window.confirm("Do you really want to delete?")) { db.collection("users").doc(id).delete().then(() => { console.log("Document deleted!"); }) .catch((error) => { console.error(error); }) } } } } </script> <style> .btn-primary { margin-right: 12px; } </style> Update Data in Cloud Firestore The $route.params.id gets the current user’s object id from the URL. Pass it inside the doc() method and access the get() function to render the single document from the Firestore database. The onUpdateForm() function updates the Firestore data object in the data collection. The user redirects to the user’s list view page once successfully updated. Add the following code inside the UserEdit.vue file. <template> <div class="row justify-content-center"> <div class="col-md-5"> <h3 class="text-center">Update User</h3> <form @submit.prevent="onUpdateForm"> <div class="form-group"> <label>Name</label> <input type="text" class="form-control" v-model="user.name" required> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control" v-model="user.email" required> </div> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control" v-model="user.phone" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block">Add User</button> </div> </form> </div> </div> </template> <script> import { db } from '../firebaseDb'; export default { data() { return { user: { } } }, created() { let dbRef = db.collection('users').doc(this.$route.params.id); dbRef.get().then((doc) => { this.user = doc.data(); }).catch((error) => { console.log(error) }) }, methods: { onUpdateForm(event) { event.preventDefault() db.collection('users').doc(this.$route.params.id) .update(this.user).then(() => { console.log("User successfully updated!"); this.$router.push('/list') }).catch((error) => { console.log(error); }); } } } </script> i hope you like this article.
Make Authentication System with VueJs and Google Firebase
In this tutorial, we will learn how to integrate Firebase Authentication in Vue.js 2+ application. We will additionally learn to register a utilizer, authenticate a utilizer and send password reset mail and logout from firebase app utilizing Vue.js application. We will utilize Firebase database to integrate authentication in Vue project from scratch. Firebase is a robust genuine-time database which offers Backend-as-a-accommodation. Firebase offers tons of utilizer authentication features such as Signin/Signup with Email and Password, Facebook, Google, Twitter, GitHub, Phone Number etc. In this tutorial, we’ll be engendering a rudimentary Vue app from scratch, integrating Firebase to vue app. We’ll engender the utilizer registration, utilizer authenticate with email/password, forgot password, logout utilizing sundry vue.js components and Firebase utilizer authentication API. If you are an abecedarian in Vue front-end development, then you must check out the following topics that we have covered anteriorly. Install and Setup Vue Project Install latest version of Vue CLI to getting started with Vue. # npm npm install -g @vue/cli # yarn yarn global add @vue/cli Create a new Vue project and get inside of it using below command. vue create vue-firebase-auth && cd vue-firebase-auth Start VUE app by using following command: npm run serve Add Bootstrap & Global CSS in Vue Install Bootstrap 4 module in Vue project. npm install bootstrap # or yarn add bootstrap Open main.js file and import the Bootstrap path inside of it. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Next, include global styling in a Vue app. Create src/assets/css folder then create the main.css file. Add the global CSS path inside the main.js file right after the Bootstrap path. import Vue from 'vue' import App from './App.vue' import router from './router' import 'bootstrap/dist/css/bootstrap.min.css' import '@/assets/css/main.css' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app') Add the following styling code in assets/css/main.css file. * { box-sizing: border-box; } body { background: #2554FF !important; min-height: 100vh; display: flex; font-weight: 400; } body, html, .App, .vue-tempalte, .vertical-center { width: 100%; height: 100%; } .navbar-light { background-color: #ffffff; box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2); } .vertical-center { display: flex; text-align: left; justify-content: center; flex-direction: column; } .inner-block { width: 450px; margin: auto; background: #ffffff; box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2); padding: 40px 55px 45px 55px; border-radius: 15px; transition: all .3s; } .vertical-center .form-control:focus { border-color: #2554FF; box-shadow: none; } .vertical-center h3 { text-align: center; margin: 0; line-height: 1; padding-bottom: 20px; } label { font-weight: 500; } .forgot-password, .forgot-password a { text-align: right; font-size: 13px; padding-top: 10px; color: #7a7a7a; margin: 0; } .forgot-password a { color: #2554FF; } .social-icons { text-align: center; font-family: "Open Sans"; font-weight: 300; font-size: 1.5em; color: #222222; } .social-icons ul { list-style: none; margin: 0; padding: 0; } .social-icons ul li { display: inline-block; zoom: 1; width: 65px; vertical-align: middle; border: 1px solid #e3e8f9; font-size: 15px; height: 40px; line-height: 40px; margin-right: 5px; background: #f4f6ff; } .social-icons ul li a { display: block; font-size: 1.4em; margin: 0 5px; text-decoration: none; } .social-icons ul li a i { -webkit-transition: all 0.2s ease-in; -moz-transition: all 0.2s ease-in; -o-transition: all 0.2s ease-in; -ms-transition: all 0.2s ease-in; transition: all 0.2s ease-in; } .social-icons ul li a:focus i, .social-icons ul li a:active i { transition: none; color: #222222; } Create Components for Firebase Authentication To manage the Firebase authentication in Vue app, we need to create the following components. Go to src/components folder and create the following files. Login.vue Signup.vue Home.vue ForgotPassword.vue An example of Vue component. <template> <div> <!-- Content goes here --> </div> </template> <script> export default { data() { return {...} } } </script> Create Routers and Enable Navigation Go to src/router/index.js file and replace with the existing code. import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/', name: 'signup', component: () => import('../components/Signup.vue') }, { path: '/login', name: 'login', component: () => import('../components/Login.vue') }, { path: '/forgot-password', name: 'forgot-password', component: () => import('../components/ForgotPassword.vue') }, { path: '/home', name: 'home', component: () => import('../components/Home.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router We are all set with the /signup, /login, /forgort-password and /home routes next we will create a navigation header using Bootstrap nav-bar component. Open src/App.vue file and the following code. <template> <div class="vue-tempalte"> <!-- Navigation --> <nav class="navbar shadow bg-white rounded justify-content-between flex-nowrap flex-row fixed-top"> <div class="container"> <a class="navbar-brand float-left" href="https://laravelcode.com" target="_blank"> LaravelCode </a> <ul class="nav navbar-nav flex-row float-right"> <li class="nav-item"> <router-link class="nav-link pr-3" to="/login">Sign in</router-link> </li> <li class="nav-item"> <router-link class="btn btn-outline-primary" to="/">Sign up</router-link> </li> </ul> </div> </nav> <!-- Main --> <div class="App"> <div class="vertical-center"> <div class="inner-block"> <router-view /> </div> </div> </div> </div> </template> Set up Firebase Project We need to create a Firebase project to get started with Vue and Firebase Authentication. Go to console.firebase.google.com to create a Firebase project. Click “Create a project”. Click on “Continue” to generate the project. Click on the web icon. Enter the project name and click on “Next” Take Firebase configuration details we will need it later to connect Vue with Firebase. Click on “Authentication”. As we can see, Firebase is offering lots of authentication providers that can easily allow you to authenticate using social channels, email/password and phone number. We only need to enable the Email/Password auth provider. Add Firebase in Vue To add the Firebase in the Vue app, we need to install the Firebase plugin using the following command. npm install firebase Next, go to main.js file here we have to import the Firebase module and add the Firebase configuration details. import Vue from 'vue' import App from './App.vue' import router from './router' import * as firebase from 'firebase'; import 'bootstrap/dist/css/bootstrap.min.css' import '@/assets/css/main.css' Vue.config.productionTip = false const firebaseConfig = { apiKey: "api-key", authDomain: "project-id.firebaseapp.com", databaseURL: "https://project-id.firebaseio.com", projectId: "project-id", storageBucket: "project-id.appspot.com", messagingSenderId: "sender-id", appId: "app-id", measurementId: "G-measurement-id" } firebase.initializeApp(firebaseConfig); new Vue({ router, render: h => h(App) }).$mount('#app') User Registration with Email/Password We are going to register a user with the name, email and password. Open the src/components/Signup.vue file and place the following code. <template> <div class="vue-tempalte"> <form @submit.prevent="userRegistration"> <h3>Sign Up</h3> <div class="form-group"> <label>Name</label> <input type="text" class="form-control form-control-lg" v-model="user.name" /> </div> <div class="form-group"> <label>Email</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control form-control-lg" v-model="user.password" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block"> Sign Up </button> <p class="forgot-password text-right"> Already registered <router-link :to="{name: 'login'}">sign in?</router-link> </p> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { name: '', email: '', password: '' } }; }, methods: { userRegistration() { firebase .auth() .createUserWithEmailAndPassword(this.user.email, this.user.password) .then((res) => { res.user .updateProfile({ displayName: this.user.name }) .then(() => { this.$router.push('/login') }); }) .catch((error) => { alert(error.message); }); } } }; </script> To create a new user account via Vue frontend with a name, email and password fields, we took the following approach. We created a new sign-up form in Vue with Bootstrap. To register a new user, we called createUserWithEmailAndPassword() method and passed user email and password. Vue Firebase Login Example Let’s implement user login in Vue app with Firebase API, we need correct email and password to access in the app. So, Open the src/components/Login.vue file and include the following code. <template> <div class="vue-tempalte"> <form @submit.prevent="userLogin"> <h3>Sign In</h3> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control form-control-lg" v-model="user.password" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block">Sign In</button> <p class="forgot-password text-right mt-2 mb-4"> <router-link to="/forgot-password">Forgot password ?</router-link> </p> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { email: '', password: '' } }; }, methods: { userLogin() { firebase .auth() .signInWithEmailAndPassword(this.user.email, this.user.password) .then(() => { this.$router.push('/home') }) .catch((error) => { alert(error.message); }); } } }; </script> We are using signInWithEmailAndPassword(email, password) method and passing the registered email address and correct password to make the user login to our vue app. Send Password Reset Email Open the components/ForgotPassword.vue component and add the following code inside of it. <template> <div class="vue-tempalte"> <form @submit.prevent="forgetPassword"> <h3>Forgot Password</h3> <div class="form-group"> <label>Email</label> <input type="email" class="form-control form-control-lg" v-model="user.email" /> </div> <button type="submit" class="btn btn-dark btn-lg btn-block">Reset password</button> </form> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: { email: '' } }; }, methods: { forgetPassword() { firebase .auth() .sendPasswordResetEmail(this.user.email) .then(() => { alert('Check your registered email to reset the password!') this.user = { email: '' } }).catch((error) => { alert(error) }) } } }; </script> The sendPasswordResetEmail(email) method takes email id, and when it is appropriately called, it sends the password reset instruction on the registered email id. User Logout and Display Logged in User Data We are going to cover up how to logout from the Firebase and Vue app and display the logged in user’s data. Open the src/components/Home.vue file and place the following code. <template> <div class="vue-tempalte"> <h3>Welcome</h3> <p>{{user.displayName}}</p> <p>{{user.email}}</p> <button type="submit" class="btn btn-dark btn-lg btn-block" @click="logOut()"> Log out </button> </div> </template> <script> import firebase from "firebase"; export default { data() { return { user: null }; }, created() { firebase.auth().onAuthStateChanged((user) => { if (user) { this.user = user; } else { this.user = null; } }); }, methods: { logOut() { firebase.auth().signOut().then(() => { firebase.auth().onAuthStateChanged(() => { this.$router.push('/login') }) }) } } }; </script> In the given above source code, we are getting the logged-in user’s data when the auth state is changing. The auth.signOut() method logs out the user from the firebase app.
How to Build Multi Language App in Vue.js
This is a step by step Vue i18n tutorial, In this tutorial, we are going to learn how to translate the Vue.js app in multi-language utilizing the vue-i18n plugin. Integrating internationalization support in the web application is auxiliary for the audience that visits our site from the sundry part of the world. Since the people in the world use variants of languages, so, it becomes compulsory for us to accommodate our site content in the same language they verbalize. Fortuitously, we can take benefit of i18n support to integrate multiple language support in our vue application; this way, we can facilely engage an immensely colossal number of audience. We will engender a pretty rudimentary multilingual vue app from scratch utilizing vue cli and vue-i18n plugin. We will learn to integrate support for English, Belarusian, Danish and Croatian. Setup Vue App Install Vue CLI to get started with Vue app development. npm install -g @vue/cli # or yarn global add @vue/cli Create a new vue project and get inside the project folder: vue create vue-i18-app && cd vue-i18-app Run the vue app. npm run serve Add Vue-i18n Plugin in Vue We have set up the vue project, and now we have to install the vue-i18n plugin using either of the command based on the package manger we prefer: # npm npm install vue-i18n # Yarn yarn add vue-i18n Vue I18n is quite popular internationalization plugin for Vue.js, and It quickly integrates localization features to your Vue.js application. It is created by kazuya kawaguchi, and you can check the official documentation of this plugin here. Now, we have to add the vue-i18n plugin in our vue.js app, so import the VueI18n package in in the main.js file. import Vue from 'vue' import App from './App.vue' import router from './router' import VueI18n from 'vue-i18n'; Vue.use(VueI18n); new Vue({ router, render: h => h(App), }).$mount('#app') Create Multi-Language Component Create components/Multilingual.vue file and add the following code in it. <template> <div> {{ $t('message.value', { value: 'This is an example of content translation' }) }} </div> </template> <script> export default { name: 'Multilingual' } </script> We define the default English message value in the $t instance. We can initiate the $t instance. This allows us to use mustash syntax {{}} in the vue template. The $t is executed whenever re-render occurs, so it does have translation costs. Define Translations in Vue We can easily format the strings with the help of vue-18n module with bracket syntax. We defined the messages object with four international languages; this object translates the vue app based on selected locale. We also have to initialize the VueI18n instance by adding the values that we defined in the messages object. Add the following code in the main.js file. import Vue from 'vue' import App from './App.vue' import router from './router' import VueI18n from 'vue-i18n'; Vue.use(VueI18n); const messages = { en: { message: { value: 'This is an example of content translation.' } }, be: { message: { value: 'Гэта прыклад перакладу змесціва.' } }, da: { message: { value: 'Dette er et eksempel på oversættelse af indhold.' } }, hr: { message: { value: 'Ovo je primjer prevođenja sadržaja.' } } }; const i18n = new VueI18n({ locale: 'en', messages }); Vue.config.productionTip = false new Vue({ router, render: h => h(App), i18n }).$mount('#app') Create Language Switcher in Vue Create components/SwitchLanguage.vue file here we define the following code. We have to add a language switcher, and we can add it by creating a simple select dropdown. This switcher allows us to change the language in our vue app, and we take the help of i18n instance via $i18n.locale. The above code will create a dropdown with the following values, ‘en’, ‘be’, ‘da’, ‘hr’. <template> <div> <select v-model="$i18n.locale"> <option v-for="(lang, i) in langs" :key="`lang-${i}`" :value="lang"> {{ lang }} </option> </select> </div> </template> <script> export default { name: 'SwitchLocale', data() { return { langs: ['en', 'be', 'da', 'hr'] } } } </script> <style> select { width: 150px; line-height: 49px; height: 38px; font-size: 22px; outline: 0; margin-bottom: 15px; } </style> To call the components in the home page just add the following code in the Home.vue app. <template> <div> <SwitchLanguage /> <Multilingual /> </div> </template> <script> import Multilingual from '@/components/Multilingual.vue' import SwitchLanguage from '@/components/SwitchLanguage.vue' export default { name: 'Home', components: { SwitchLanguage, Multilingual } } </script> i hope you like this article.
Laravel 5.5 - VueJS 2.0 CRUD Operations
Today, we are share with you VueJS 2.0 CRUD (insert, update, delete and listing) oparation in laravel 5.5, we all are known laravel 5.5 and VueJS 2.0 is best combination for development any web application. in this article we are show you how to make laravel 5.5 and VueJS 2.0 crud in step by step don't warry if you are beginner, intermediate or expert in laravel or VueJS. simply follow this all step any easyly make VueJS 2.0 CRUD with laravel 5.5 Before starting vuejs crud with laravel you required following things in your system. Development Server Requirements: PHP >= 7.0.0 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension Apache/Nginx MySQl Composer NodeJs with NPM Step : 1 Create Laravel Project: First, we need to create one laravel fresh project using composer. simply run following command in your terminal for create new laravel project. composer create-project --prefer-dist laravel/laravel ProjectName Step : 2 Configure .env Next, after create laravel project open .env file and configure your database setting like that. DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=YOUR-DATABASE-NAME DB_USERNAME=DATABASE-USERNAME DB_PASSWORD=DATABASE-USER-PASSWORD Step : 3 Create Post Table Migration: Next, we are create one post table migration for make all crud oparation on it. simple run following command and create migration file. php artisan make:migration create_post_table --create=posts After create migration open migration file and make change in it like that. use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } } Then run migration using following command. php artisan migrate Step : 4 Create Post Table Model And Controller: Next, we are create Post table model and controller run by following command. php artisan make:model Post -r You can locate the model at /app/Post.php and controller at /app/Http/Controllers/PostController.php Next, open your model app/Post.php file and make following change. namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = [ 'title', 'description', ]; } app/Http/Controllers/PostController.php namespace App\Http\Controllers; use App\Post; use Illuminate\Http\Request; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::get(); return response()->json([ 'posts' => $posts, ], 200); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'title' => 'required|max:255', 'description' => 'required', ]); $post = Post::create([ 'title' => request('title'), 'description' => request('description'), ]); return response()->json([ 'post' => $post, 'message' => 'Success' ], 200); } /** * Display the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function show(Post $post) { // } /** * Show the form for editing the specified resource. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function edit(Post $post) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Post $post * @return \Illuminate\Http\Response */ public function update(Request $request, Post $post) { $this->validate($request, [ 'title' => 'required|max:255', 'description' => 'required', ]); $post->title = request('title'); $post->description = request('description'); $post->save(); return response()->json([ 'message' => 'Post updated successfully!' ], 200); } /** * Remove the specified resource from storage. * * @param \App\Post $post * @return \Illuminate\Http\Response */ public function destroy(Post $post) { // } } Step : 5 Create Post Route: Next, we need to create insert, update, index, delete, create routes for this crud. we are make crud so resource route is best. i hope you all are very well known resource Route. Route::resource('/posts', 'PostController'); Step : 6 Register Vue Component: Next, we are need to register vuejs component in /resources/assets/js/app.js file open it and make following changes /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('example', require('./components/Example.vue')); Vue.component('posts', require('./components/Post.vue')); const app = new Vue({ el: '#app' }); After add component open your /resources/views/home.blade.php file and make following changes @extends('layouts.app') @section('content') <posts></posts> @endsection Step : 7 Create New VueJS Component: Next, we are use here vue js 2.0 for front. and we all are known laravel provide bydefault setting for vue js for easy to develope front layout. Here, we are create one vue js component file Post.vue in /resources/assets/js/components/ folder [ADDCODE] <template> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading">My Post</div> <div class="panel-body"> </div> </div> </div> </div> </div> </template> <template> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <button @click="initAddPost()" class="btn btn-primary btn-xs pull-right"> + Add New Post </button> My Post </div> <div class="panel-body"> <table class="table table-bordered table-striped table-responsive" v-if="posts.length > 0"> <tbody> <tr> <th> No. </th> <th> Title </th> <th> Description </th> <th> Action </th> </tr> <tr v-for="(posts, index) in posts"> <td>{{ index + 1 }}</td> <td> {{ posts.title }} </td> <td> {{ posts.description }} </td> <td> <button @click="initUpdate(index)" class="btn btn-success btn-xs">Edit</button> <button @click="deletePost(index)" class="btn btn-danger btn-xs">Delete</button> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="modal fade" tabindex="-1" role="dialog" id="add_post_model"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">Add New Post</h4> </div> <div class="modal-body"> <div class="alert alert-danger" v-if="errors.length > 0"> <ul> <li v-for="error in errors">{{ error }}</li> </ul> </div> <div class="form-group"> <label for="title">Title:</label> <input type="text" name="title" id="title" placeholder="Title Name" class="form-control" v-model="posts.title"> </div> <div class="form-group"> <label for="description">Description:</label> <textarea name="description" id="description" cols="30" rows="5" class="form-control" placeholder="Post Description" v-model="posts.description"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" @click="createPost" class="btn btn-primary">Submit</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <div class="modal fade" tabindex="-1" role="dialog" id="update_post_model"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title">Update Post</h4> </div> <div class="modal-body"> <div class="alert alert-danger" v-if="errors.length > 0"> <ul> <li v-for="error in errors">{{ error }}</li> </ul> </div> <div class="form-group"> <label>Title:</label> <input type="text" placeholder="Title" class="form-control" v-model="update_post.title"> </div> <div class="form-group"> <label for="description">Description:</label> <textarea cols="30" rows="5" class="form-control" placeholder="Task Description" v-model="update_post.description"></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" @click="updatePost" class="btn btn-primary">Submit</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> </div> </template> <script> export default { data(){ return { posts: { title: '', description: '' }, errors: [], posts: [], update_post: {} } }, mounted() { this.readPosts(); }, methods: { initAddPost() { this.errors = []; $("#add_post_model").modal("show"); }, createPost() { axios.post('/posts', { title: this.posts.title, description: this.posts.description, }) .then(response => { this.reset(); $("#add_post_model").modal("hide"); }) .catch(error => { this.errors = []; if (error.response.data.errors.title) { this.errors.push(error.response.data.errors.title[0]); } if (error.response.data.errors.description) { this.errors.push(error.response.data.errors.description[0]); } }); }, reset() { this.posts.title = ''; this.posts.description = ''; }, readPosts() { axios.get('/posts') .then(response => { this.posts = response.data.posts; }); }, initUpdate(index) { this.errors = []; $("#update_post_model").modal("show"); this.update_post = this.posts[index]; }, updatePost() { axios.patch('/posts/' + this.update_post.id, { title: this.update_post.title, description: this.update_post.description, }) .then(response => { $("#update_post_model").modal("hide"); }) .catch(error => { this.errors = []; if (error.response.data.errors.title) { this.errors.push(error.response.data.errors.title[0]); } if (error.response.data.errors.description) { this.errors.push(error.response.data.errors.description[0]); } }); }, deletePost(index) { let conf = confirm("Do you ready want to delete this post?"); if (conf === true) { axios.delete('/posts/' + this.posts[index].id) .then(response => { this.posts.splice(index, 1); }) .catch(error => { }); } } } } </script> Step : 8 How To Run: Our crud oparation run now how to run it. please simple follow this step. run following command for install npm dependancy npm install Now run following command for deploy nmp setup and Compile Assets and Use Post Controller: npm run dev Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000/ Now, register new user and you see your VueJS crud If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...
Real Time Comment System With Laravel And Vuejs
Today, Laravelcode share sommething new and very usefull tutorials with every one. Realtime comment system built using laravel and vuejs. comment system required every website. so, we are created here comment system with some awesome functionality. when user comment and post it then instently comment show in the page. In this tutorials we are create one sapareted comment module and in this comment module we are cover following functionality. after user register then they will be able to do all functionality or action. NOTE : In this tutorials we are not adding some file like css, we are cover some basiv stuff in this tutorials. if you get woring code so, please download from my github account we are also add link here Download working code Add new comments Reply to comments Up and Down votes Mark spam comments In this our tutorials for make comment system we are using following technologies : Bootstrap Loadash Vue-resource Laravel Mix Now we are starting our comment system tutorials step by step. Step : 1 Create comments table migration First, we need to create comment table for stare all comment data and aslo span and comment voting data. so, create new one migration by following command. php artisan make:migration comments Now copy following migration code and past in your migration file. Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->text('comment'); $table->integer('votes')->default(0); $table->integer('spam')->default(0); $table->integer('reply_id')->default(0); $table->string('page_id')->default(0); $table->integer('users_id'); $table->timestamps(); }); Schema::create('comment_user_vote', function (Blueprint $table) { $table->integer('comment_id'); $table->integer('user_id'); $table->string('vote',11); }); Schema::create('comment_spam', function (Blueprint $table) { $table->integer('comment_id'); $table->integer('user_id'); }); Now run your migration file using following command php artisan migrate Step : 2 Create Auth for Comment System Now, we are created laravel built-in auth system using following command php artisan make:auth Step : 3 Create Models for the Comment System Now, we are created model for comments table by run followign command php artisan make:model Comment Then open your app/Comment.php file and put into it following code. namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $fillable = ['comment','votes','spam','reply_id','page_id','users_id']; protected $dates = ['created_at', 'updated_at']; public function replies() { return $this->hasMany('App\Comment','id','reply_id'); } } In above code we are define required fillable columns fields with $fillable and create one replies() method which has the one-many relationship with own. Now create a model for comment_user_vote. Run the following command: php artisan make:model CommentVote Now open your app/CommentVote.php file and put into following code. namespace App; use Illuminate\Database\Eloquent\Model; class CommentVote extends Model { protected $fillable = ['comment_id','user_id','vote']; protected $table = "comment_user_vote"; public $timestamps = false; } Now, create last one model for comment_spam table php artisan make:model CommentSpam Now open your app/CommentSpam.php file and put into following code. namespace App; use Illuminate\Database\Eloquent\Model; class CommentSpam extends Model { protected $fillable = ['comment_id','user_id']; protected $table = "comment_spam"; public $timestamps = false; } Step : 4 Create the Routes for Comments Now, we are creating following route for required in out comment system. open your routes/web.php and past following route in it. Route::get('/{pageId}', function($pageId) { return view('page',['pageId' => $pageId]); }); // Route for index page Route::get('comments/{pageId}', 'CommentController@index'); // Route for store comment Route::post('comments', 'CommentController@store'); // Route for update comment Route::post('comments/{commentId}/{type}', 'CommentController@update'); Step : 5 Create the Controller for Comment Now, create controller for comment by run following command : php artisan make:controller CommentController After run this command then your controller file automatic generated in app/Http/Controllers/CommentController.php open it and place in it following code. namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Comment; use App\CommentVote; use App\CommentSpam; class CommentController extends Controller { public function index($pageId) { // $comments = Comment::where('page_id',$pageId)->get(); $commentsData = []; foreach ($comments as $key) { $user = User::find($key->users_id); $name = $user->name; $replies = $this->replies($key->id); $photo = $user->first()->photo_url; // dd($photo->photo_url); $reply = 0; $vote = 0; $voteStatus = 0; $spam = 0; if(Auth::user()) { $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first(); $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first(); if($voteByUser) { $vote = 1; $voteStatus = $voteByUser->vote; } if($spamComment) { $spam = 1; } } if(sizeof($replies) > 0) { $reply = 1; } if(!$spam) { array_push($commentsData,[ "name" => $name, "photo_url" => (string)$photo, "commentid" => $key->id, "comment" => $key->comment, "votes" => $key->votes, "reply" => $reply, "votedByUser" =>$vote, "vote" =>$voteStatus, "spam" => $spam, "replies" => $replies, "date" => $key->created_at->toDateTimeString() ]); } } $collection = collect($commentsData); return $collection->sortBy('votes'); } protected function replies($commentId) { $comments = Comment::where('reply_id',$commentId)->get(); $replies = []; foreach ($comments as $key) { $user = User::find($key->users_id); $name = $user->name; $photo = $user->first()->photo_url; $vote = 0; $voteStatus = 0; $spam = 0; if(Auth::user()) { $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first(); $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first(); if($voteByUser) { $vote = 1; $voteStatus = $voteByUser->vote; } if($spamComment) { $spam = 1; } } if(!$spam) { array_push($replies,[ "name" => $name, "photo_url" => $photo, "commentid" => $key->id, "comment" => $key->comment, "votes" => $key->votes, "votedByUser" => $vote, "vote" => $voteStatus, "spam" => $spam, "date" => $key->created_at->toDateTimeString() ]); } $collection = collect($replies); return $collection->sortBy('votes'); } public function store(Request $request) { $this->validate($request, [ 'comment' => 'required', 'reply_id' => 'filled', 'page_id' => 'filled', 'users_id' => 'required', ]); $comment = Comment::create($request->all()); if($comment) return [ "status" => "true","commentId" => $comment->id ]; } public function update(Request $request, $commentId, $type) { if($type == "vote"){ $this->validate($request, [ 'vote' => 'required', 'users_id' => 'required', ]); $comments = Comment::find($commentId); $data = [ "comment_id" => $commentId, 'vote' => $request->vote, 'user_id' => $request->users_id, ]; if($request->vote == "up"){ $comment = $comments->first(); $vote = $comment->votes; $vote++; $comments->votes = $vote; $comments->save(); } if($request->vote == "down"){ $comment = $comments->first(); $vote = $comment->votes; $vote--; $comments->votes = $vote; $comments->save(); } if(CommentVote::create($data)) return "true"; } if($type == "spam") { $this->validate($request, [ 'users_id' => 'required', ]); $comments = Comment::find($commentId); $comment = $comments->first(); $spam = $comment->spam; $spam++; $comments->spam = $spam; $comments->save(); $data = [ "comment_id" => $commentId, 'user_id' => $request->users_id, ]; if(CommentSpam::create($data)) return "true"; } } } Step : 6 Comment Component Using VueJS [ADDCODE] Run following command for install all package.json file dependencies. npm install Now, we are required vue-resource so, run following command for it npm install --save vue-resource Now, go to the this path resources/assets/js/components and create one blank file Comments.vue. now leave it blank. and open your resources/assets/js/app.js and add following code. Add the following line after require('./bootstrap'); import VueResource from "vue-resource" Now, Add the following line after window.Vue = require('vue'); Vue.use(VueResource); Vue.component('comment', require('./components/Comments.vue')); Step : 6 Write Code For Comments.vue We are already create Comments.vue file before but then we are not put any code in it so, open Comments.vue file and put into following templet code <template> <div class="comments-app"> <h1>Comments</h1> <!-- From --> <div class="comment-form" v-if="user"> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/commentbox.png"> </div> <form class="form" name="form"> <div class="form-row"> <textarea class="input" placeholder="Add comment..." required v-model="message"></textarea> <span class="input" v-if="errorComment" style="color:red">{{errorComment}}</span> </div> <div class="form-row"> <input class="input" placeholder="Email" type="text" disabled :value="user.name"> </div> <div class="form-row"> <input type="button" class="btn btn-success" @click="saveComment" value="Add Comment"> </div> </form> </div> <div class="comment-form" v-else> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/commentbox.png"> </div> <form class="form" name="form"> <div class="form-row"> <a href="login"> <textarea class="input" placeholder="Add comment..." required></textarea> </a> </div> </form> </div> <!-- Comments List --> <div class="comments" v-if="comments" v-for="(comment,index) in commentsData"> <!-- Comment --> <div v-if="!spamComments[index] || !comment.spam" class="comment"> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/comment.png"> </div> <!-- Comment Box --> <div class="comment-box"> <div class="comment-text">{{comment.comment}}</div> <div class="comment-footer"> <div class="comment-info"> <span class="comment-author"> <em>{{ comment.name}}</em> </span> <span class="comment-date">{{ comment.date}}</span> </div> <div class="comment-actions"> <ul class="list"> <li>Votes: {{comment.votes}} <a v-if="!comment.votedByUser" v-on:click="voteComment(comment.commentid,'directcomment',index,0,'up')">Up Votes</a> <a v-if="!comment.votedByUser" v-on:click="voteComment(comment.commentid,'directcomment',index,0,'down')">Down Votes</a> </li> <li> <a v-on:click="spamComment(comment.commentId,'directcomment',index,0)">Spam</a> </li> <li> <a v-on:click="openComment(index)">Reply</a> </li> </ul> </div> </div> </div>= <!-- From --> <div class="comment-form comment-v" v-if="commentBoxs[index]"> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/comment.png"> </div> <form class="form" name="form"> <div class="form-row"> <textarea class="input" placeholder="Add comment..." required v-model="message"></textarea> <span class="input" v-if="errorReply" style="color:red">{{errorReply}}</span> </div> <div class="form-row"> <input class="input" placeholder="Email" type="text" :value="user.name"> </div> <div class="form-row"> <input type="button" class="btn btn-success" v-on:click="replyComment(comment.commentid,index)" value="Add Comment"> </div> </form> </div> <!-- Comment - Reply --> <div v-if="comment.replies"> <div class="comments" v-for="(replies,index2) in comment.replies"> <div v-if="!spamCommentsReply[index2] || !replies.spam" class="comment reply"> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/comment.png"> </div> <!-- Comment Box --> <div class="comment-box" style="background: grey;"> <div class="comment-text" style="color: white">{{replies.comment}}</div> <div class="comment-footer"> <div class="comment-info"> <span class="comment-author"> {{replies.name}} </span> <span class="comment-date">{{replies.date}}</span> </div> <div class="comment-actions"> <ul class="list"> <li>Total votes: {{replies.votes}} <a v-if="!replies.votedByUser" v-on:click="voteComment(replies.commentid,'replycomment',index,index2,'up')">Up Votes</a> <a v-if="!replies.votedByUser" v-on:click="voteComment(comment.commentid,'replycomment',index,index2,'down')">Down Votes</a> </a> </li> <li> <a v-on:click="spamComment(replies.commentid,'replycomment',index,index2)">Spam</a> </li> <li> <a v-on:click="replyCommentBox(index2)">Reply</a> </li> </ul> </div> </div> </div> <!-- From --> <div class="comment-form reply" v-if="replyCommentBoxs[index2]"> <!-- Comment Avatar --> <div class="comment-avatar"> <img src="storage/comment.png"> </div> <form class="form" name="form"> <div class="form-row"> <textarea class="input" placeholder="Add comment..." required v-model="message"></textarea> <span class="input" v-if="errorReply" style="color:red">{{errorReply}}</span> </div> <div class="form-row"> <input class="input" placeholder="Email" type="text" :value="user.name"> </div> <div class="form-row"> <input type="button" class="btn btn-success" v-on:click="replyComment(comment.commentid,index)" value="Add Comment"> </div> </form> </div> </div> </div> </div> </div> </div> </div> </template> Step : 6 Add Script For Comments.vue Now add following script code in Comments.vue file after closing template tag. <script> var _ = require('lodash'); export default { props: ['commentUrl'], data() { return { comments: [], commentreplies: [], comments: 0, commentBoxs: [], message: null, replyCommentBoxs: [], commentsData: [], viewcomment: [], show: [], spamCommentsReply: [], spamComments: [], errorComment: null, errorReply: null, user: window.user } }, http: { headers: { 'X-CSRF-TOKEN': window.csrf } }, methods: { fetchComments() { this.$http.get('comments/' + this.commentUrl).then(res => { this.commentData = res.data; this.commentsData = _.orderBy(res.data, ['votes'], ['desc']); this.comments = 1; }); }, showComments(index) { if (!this.viewcomment[index]) { Vue.set(this.show, index, "hide"); Vue.set(this.viewcomment, index, 1); } else { Vue.set(this.show, index, "view"); Vue.set(this.viewcomment, index, 0); } }, openComment(index) { if (this.user) { if (this.commentBoxs[index]) { Vue.set(this.commentBoxs, index, 0); } else { Vue.set(this.commentBoxs, index, 1); } } }, replyCommentBox(index) { if (this.user) { if (this.replyCommentBoxs[index]) { Vue.set(this.replyCommentBoxs, index, 0); } else { Vue.set(this.replyCommentBoxs, index, 1); } } }, saveComment() { if (this.message != null && this.message != ' ') { this.errorComment = null; this.$http.post('comments', { page_id: this.commentUrl, comment: this.message, users_id: this.user.id }).then(res => { if (res.data.status) { this.commentsData.push({ "commentid": res.data.commentId, "name": this.user.name, "comment": this.message, "votes": 0, "reply": 0, "replies": [] }); this.message = null; } }); } else { this.errorComment = "Please enter a comment to save"; } }, replyComment(commentId, index) { if (this.message != null && this.message != ' ') { this.errorReply = null; this.$http.post('comments', { comment: this.message, users_id: this.user.id, reply_id: commentId }).then(res => { if (res.data.status) { if (!this.commentsData[index].reply) { this.commentsData[index].replies.push({ "commentid": res.data.commentId, "name": this.user.name, "comment": this.message, "votes": 0 }); this.commentsData[index].reply = 1; Vue.set(this.replyCommentBoxs, index, 0); Vue.set(this.commentBoxs, index, 0); } else { this.commentsData[index].replies.push({ "commentid": res.data.commentId, "name": this.user.name, "comment": this.message, "votes": 0 }); Vue.set(this.replyCommentBoxs, index, 0); Vue.set(this.commentBoxs, index, 0); } this.message = null; } }); } else { this.errorReply = "Please enter a comment to save"; } }, voteComment(commentId, commentType, index, index2, voteType) { if (this.user) { this.$http.post('comments/' + commentId + '/vote', { users_id: this.user.id, vote: voteType }).then(res => { if (res.data) { if (commentType == 'directcomment') { if (voteType == 'up') { this.commentsData[index].votes++; } else if (voteType == 'down') { this.commentsData[index].votes--; } } else if (commentType == 'replycomment') { if (voteType == 'up') { this.commentsData[index].replies[index2].votes++; } else if (voteType == 'down') { this.commentsData[index].replies[index2].votes--; } } } }); } }, spamComment(commentId, commentType, index, index2) { console.log("spam here"); if (this.user) { this.$http.post('comments/' + commentId + '/spam', { users_id: this.user.id, }).then(res => { if (commentType == 'directcomment') { Vue.set(this.spamComments, index, 1); Vue.set(this.viewcomment, index, 1); } else if (commentType == 'replycomment') { Vue.set(this.spamCommentsReply, index2, 1); } }); } }, }, mounted() { console.log("mounted"); this.fetchComments(); } } </script> NOTE : In this tutorials we are not adding some file like css, we are cover some basiv stuff in this tutorials. if you get woring code so, please download from my github account we are also add link here Download working code Now we are ready to run our example so run bellow command ro quick run: php artisan serve Now you can open bellow URL on your browser: http://localhost:8000 If you face any problem then please write a comment or give some suggestions for improvement. Thanks...