article

Showing posts with label Vue CLI. Show all posts
Showing posts with label Vue CLI. Show all posts

Friday, March 11, 2022

Vuejs Vue CLI File Upload with Axios and PHP

Vuejs Vue CLI File Upload with Axios and PHP

Install vue-axios
npm install --save axios vue-axios
https://www.npmjs.com/package/vue-axios

C:\vuejs\myapp>npm install --save axios vue-axios
C:\vuejs\myapp>npm run serve
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'

import axios from 'axios' // C:\vuejs\myapp>npm install --save axios vue-axios

import VueAxios from 'vue-axios'


createApp(App).use(VueAxios, axios).mount('#app')
src/components/fileUpload.vue
//src/components/fileUpload.vue
<template>
  <div class="container">
    <div class="row">
      <h1>Vuejs Vue CLI File Upload with Axios and PHP</h1>
      <label>File
        <input type="file" id="file" ref="file"/>
      </label>
        <button v-on:click="uploadFile()">Upload</button>
    </div>
  </div>
</template>

<script>

  export default  {   
      data () {
      return {          
          file:''
      }    
    },
    methods: {     

            uploadFile: function(){

                 this.file = this.$refs.file.files[0];                  
                 let formData = new FormData();
                 formData.append('file', this.file);
                 this.$refs.file.value = '';
                this.axios.post('http://localhost/devtest/upload.php', formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(function (response) {

                    if(!response.data){
                        alert('File not uploaded.');
                    }else{
                        alert('File uploaded successfully.');                        

                    }

                })
                .catch(function (error) {
                    console.log(error);
                 });

            }
    },
    
}
</script>
src/App.vue
//src/App.vue
<template>
  <div id="app">
      <FileUpload/>
  </div>
</template>
<script>
import FileUpload from './components/fileUpload.vue'
 
      export default {
                 name: 'app',
                       components: {
                             FileUpload
                }
       }
</script>
upload.php
//upload.php
<?php  
    header('Access-Control-Allow-Origin: *');  
     $filename = $_FILES['file']['name'];
     $allowed_extensions = array('jpg','jpeg','png','pdf');
      $extension = pathinfo($filename, PATHINFO_EXTENSION);
       if(in_array(strtolower($extension),$allowed_extensions) ) {     
          if(move_uploaded_file($_FILES['file']['tmp_name'], "upload/".$filename)){
                echo 1;
          }else{
              echo 0;
          }
    }else{
        echo 0;
    } 
?>

Wednesday, February 23, 2022

Vue CLI How to use Vue Router

Vue CLI How to use Vue Router

# Create a new Vue project
vue create myapp
cd myapp
# start your app by running the following command
npm run serve

vue add router

C:\vuejs\myapp>vue add router

src/router/index.js
//src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Profile from '../views/Profile.vue'
import Product from '../views/Product.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
  },
  { path: '/product/:id', component: Product },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router
src/App.vue
//src/App.vue
<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link> |
    <!--<router-link to="/profile">Profile</router-link> -->
    <router-link :to="{ name: 'profile', params: { username: 'cairocoders' } }" > <!--router params -->
      Profile
    </router-link>  |
    <router-link to="/product">Product</router-link> 
  </div>
  <router-view/>
</template>
src/main.js
//src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')
src/views/Product.vue
//src/views/Product.vue
<template>
    <div class="product">
        Product Page
    </div>
    <span>
        Looking for Product: {{ this.$route.params.id }}
    </span>
</template>
src/views/Profile.vue
//src/views/Profile.vue
<template>
    <div class="profile">
        Profile Info
    </div>
    <span>
        {{ this.$route.params.username }}
    </span>
</template>

Thursday, February 17, 2022

Vue.js Vue CLI Image Upload Preview

Vue.js Vue CLI Image Upload Preview

C:\vuejs\my-vue-app>npm run serve

src/App.vue
//src/App.vue
<template>
  <div id="app">
    <h1>Vue.js Vue CLI Image Upload Preview</h1>
    <HelloWorld/>
  </div>
</template>

<script>
import HelloWorld from './components/filePreview.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
src/components/filePreview.vue
//src/components/filePreview.vue
<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>
.imagePreviewWrapper {
    width: 250px;
    height: 250px;
    display: block;
    cursor: pointer;
    margin: 0 auto 30px;
    background-size: cover;
    background-position: center center;
}
</style>

Friday, January 28, 2022

Vue CLI Install Create project and run

Vue CLI Install Create project and run

Download and install Node.js and NPM Package in your system

https://nodejs.org/en/download/
https://docs.npmjs.com/cli/v8/configuring-npm/install

check the node and npm is installed

node js:
$ node -v

version of npm
$ npm -v

Check Vue JS Verison
$ vue --version
$ vue -V

Install the Vue CLI 

https://cli.vuejs.org/

https://cli.vuejs.org/guide/installation.html

$ npm install -g @vue/cli

create a project in Vue Cli 

$ vue create my-vue-app

cd my-vue-app
$ npm run serve


Tuesday, January 11, 2022

Python Flask Vue.js Axios - List All Data

Python Flask Vue.js Axios - List All Data

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

We'll be using the Vue CLI  https://cli.vuejs.org/

$ vue create client
This will require you to answer a few questions about the project.

Vue CLI v4.5.11
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

Use the down arrow key to highlight

Run development server:
$ cd client
$ npm run serve

Install Bootstrap https://getbootstrap.com/docs/5.0/getting-started/download/
$ npm install bootstrap

Install Axios
https://github.com/axios/axios
$ npm install axios
app.py
 
from flask import Flask, jsonify
from flask_cors import CORS

MEMBERS = [
    {
        'id': '1',
        'name': 'cairocoders Ednalan',
        'email': 'cairocoders@gmail.com',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'name': 'clydey Ednalan',
        'email': 'clydey@gmail.com',
        'address': 'Angles city'
    },
    {
        'id': '3',
        'name': 'claydren Ednalan',
        'email': 'clyderen@gmail.com',
        'address': 'San Fernando city'
    }
]

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')

@app.route('/members', methods=['GET'])
def all_members():
    return jsonify({
        'status': 'success',
        'members': MEMBERS
    })

if __name__ == '__main__':
    app.run()
client/scr/main.js
//client/scr/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap/dist/css/bootstrap.css';

Vue.config.productionTip = false

new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');
client/src/App.vue
//client/src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
client/src/Ping.vue
//client/src/Ping.vue
<template>
  <div>
    <p>{{ msg }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Ping',
  data() {
    return {
      msg: '',
    };
  },
  methods: {
    getMessage() {
      const path = 'http://localhost:5000/ping';
      axios.get(path)
        .then((res) => {
          console.log(res)
          this.msg = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMessage();
  },
};
</script>
client/src/components/Home.vue
//client/src/components/Home.vue
<template>
  <div class="container">
    <div class="row">
      <div class="col-sm-10">
        <h1>Member</h1>
        <hr><br><br>
        <button type="button" class="btn btn-success btn-sm">Add Member</button>
        <br><br>
        <table class="table table-hover">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Address</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(rs, index) in members" :key="index">
              <td>{{ rs.name }}</td>
              <td>{{ rs.email }}</td>
              <td>{{ rs.address }}</td>
              <td>
                <div class="btn-group" role="group">
                  <button type="button" class="btn btn-warning btn-sm">Update</button>
                  <button type="button" class="btn btn-danger btn-sm">Delete</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      members: [],
    };
  },
  methods: {
    getMembers() {
      const path = 'http://localhost:5000/members';
      axios.get(path)
        .then((res) => {
          console.log(res);
          this.members = res.data.members;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMembers();
  },
};
</script>
client/src/router/index.js
//client/src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Ping from '../components/Ping.vue';
import Home from '../components/Home.vue';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/ping',
      name: 'Ping',
      component: Ping,
    },
  ],
});

Related Post