knaka Tech-Blog

AI, IoT, DIYエレクトロニクス, データサイエンスについて投稿予定です。

Vue.js +php, ローカルHTMLからクロスドメイン接続版 #Vue.js #web #php

index:

概要:

前のVue.js 関連で、
クロスドメイン構成の仕組みで、アプリ構築する事例となります。

以前の, Vue-CLI +firebase 構成と似ていますが。
バックエンドは、以前の自前APIサービスで
Codeigniter3 のphp軽量フレームワーク、sqlite3
の構成となります。

・ローカルのフォルダからも、htmlをブラウザ開くと
 全ての機能が使用できる。アプリ構成としました

環境

Vue.js
php7.1
sqlite3
jQuery

参考の設定

・フロント側
github.com

API
github.com

ajaxのクロスドメイン対応

ajax で、クロスドメイン通信する場合は。通常はエラーになりますが
phpで、ヘッダ情報を追加すると回避できました。

・コントローラに追加しています。

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');        

実装など

・画面間のキー情報は、localStorage
で、渡しています。

・index
https://github.com/kuc-arc-f/vue3_cros_ver1/blob/master/index.html

var baseUrl = 'http://127.0.0.1/code-3/';
console.log(baseUrl)
//
var app = new Vue({
    el: '#app',
    created() {
        this.getTasks()
        var dat = exStorage.load(sysConst.STORAGE_KEY_pageId )
        //exStorage.remove(sysConst.STORAGE_KEY_pageId)
        console.log(dat[0])
    },    
    data: {
        tasks : [],
    },
    methods: {
        getTasks() {
            var url = this.conv_url('api/tasks')
            axios.get(url)
            .then(res =>  {
                this.tasks = res.data
                //console.log(res.data.length )
            })
        },
        conv_url(url) {
            return baseUrl + url
        },
        move_url(id) {
            console.log(id)
            var store = []
            store.push({ 'id' : id })            
            exStorage.save(sysConst.STORAGE_KEY_pageId , store)
            window.location.href='show.html'
//            console.log(sysConst.STORAGE_KEY_pageId)
        }
    }    
});

・show
https://github.com/kuc-arc-f/vue3_cros_ver1/blob/master/show.html

var baseUrl = 'http://127.0.0.1/code-3/';
console.log(baseUrl)
//
var app = new Vue({
    el: '#app',
    created() {
        var dat = exStorage.load(sysConst.STORAGE_KEY_pageId )
        console.log(dat.length )
        if(dat.length < 1){
            alert('表示IDの取得に失敗しました。');
        }else{
            this.task_id= dat[0].id
        }
    },    
    data: {
        item : [],
        task_id: 0,
    },
    mounted: function() {
        this.getItem();
    },    
    methods: {
        getItem() {
            var url = this.conv_url('api/tasks/show/'+ this.task_id)
            console.log(url)
            axios.get(url)
            .then(res =>  {
                this.item = res.data
//                console.log(res.data )
            })
        },
        conv_url(url) {
            return baseUrl + url
        },
    }    
});

おまけ

・netlify.com (ホスティングサービス)で、設置した場合でも
 正常に動作しました。
・バックエンドは、LAN上の APIサービスです。

f:id:knaka0209:20190504101714p:plain

Vue.js +Codeigniter3 +sqlite 設定など

index:

概要:

前のVue.js 関連で、
バックエンドは
Codeigniter3 のphp軽量フレームワーク、sqlite3
の構成となります。

環境

Vue.js
php7.1
sqlite3
jQuery

参考の設定

github.com

準備

sqliteの設定
application\sqlite\db1.sqlite に配置した場合。

database.php
https://github.com/kuc-arc-f/code-2_ver1/blob/master/application/config/database.php

$active_group = 'sqlite';
$query_builder = TRUE;

$db['sqlite'] = array(
    'dsn'  => 'sqlite:'.APPPATH.'sqlite/db1.sqlite',
    'hostname' => '',
    'username' => '',
    'password' => '',
    'database' => '',
    'dbdriver' => 'pdo',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'autoinit' => TRUE,
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


・表の作成例

CREATE TABLE tasks(
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  title VARCHAR(255) NOT NULL,
  content TEXT,
  uid INTEGER,
  up_date TIMESTAMP
);

・index
https://github.com/kuc-arc-f/code-2_ver1/blob/master/application/views/tasks/index.php

var baseUrl = '<?php echo base_url(); ?>';

var app = new Vue({
    el: '#app',
    created() {
        this.getTasks()
    },    
    data: {
        tasks : [],
    },
    methods: {
        getTasks() {
            var url = this.conv_url('api/tasks')
            axios.get(url)
            .then(res =>  {
                this.tasks = res.data
                console.log(res.data.length )
            })
        },
        conv_url(url) {
            return baseUrl + url
        }
    }    
});


・create
https://github.com/kuc-arc-f/code-2_ver1/blob/master/application/views/tasks/create.php
登録系は、jQuery 使いました。 axios でエラー回避が困難でしたので。。

var baseUrl = '<?php echo base_url(); ?>';
console.log(baseUrl);

function test_ajax(){
    console.log('#btn-1');
    var hostUrl= baseUrl + 'api/tasks/create';
    var title = $('#title').val();
    var content = $('#content').val();
    $.ajax({
        url: hostUrl,
        type:'POST',
        dataType: 'json',
        data : { 'title' : title, 'content' : content},
        timeout:3000,
    }).done(function(data) {
        console.log("ajax-ok");
        console.log(data);
    }).fail(function(XMLHttpRequest, textStatus, errorThrown) {
        console.log("ajax-error");
    })		
}

・ルーティング
https://github.com/kuc-arc-f/code-2_ver1/blob/master/application/config/routes.php

$route['tasks/edit/(:any)'] = 'tasks/edit/$1';
$route['tasks/show/(:any)'] = 'tasks/view/$1';
$route['tasks/create'] = 'tasks/create';
$route['tasks/(:any)'] = 'tasks/view/$1';
$route['tasks'] = 'tasks';
$route['api/tasks/create'] = 'tasks/api_create';
$route['api/tasks'] = 'tasks/api_index';

Vue.js (Vue CLI 3) bootstrapの追加 SPA開発(10) #Vue.js #web #firebase #SPA

index:

概要:

前のSPA(SinglePageApplication) 関連で、
bootstrap 4.0のCSS 追加内容です

環境

Vue-CLI 3.6.6
Vue.js
vue-router
firebase
bootstrap 4.0

実装など

https://github.com/kuc-arc-f/vue_2_ver3/blob/master/public/index.html

cdn追加のみですが。

・index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>vue_2</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <!---->
  </head>
  <body>
    <noscript>
      <strong>We're sorry but vue_2 doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

画面

一覧の例となります。
少し見た目は、よくなりました
f:id:knaka0209:20190501103639p:plain

Vue.js (Vue CLI 3) 共通関数の処理 SPA開発(9) #Vue.js #web #firebase #SPA

index:

概要:

前のSPA(SinglePageApplication) 関連で、
自作した共通関数を、Vueコンポーネントから呼び出す場合の
処理となります。Mixin 使いました。

環境

Vue-CLI 3.6.6
Vue.js
vue-router
firebase

実装など

・mixin.js
https://github.com/kuc-arc-f/vue_2_ver3/blob/master/src/mixin.js

export const Mixin =  {
    created:function(){
    },
    test_func(){
        return 'ABC'
    },

  }
}

・test.vue
https://github.com/kuc-arc-f/vue_2_ver3/blob/master/src/components/Tasks/test.vue

import で、mixin 読込み。
this.test_func() で実行。

<script>
import {Mixin} from '../../mixin'

export default {
    mixins:[Mixin],
    created() {
        console.log( 'test_func='+ this.test_func() )
    },
    data() {
        return {
            user : [],
            message :''
        }
    },
    methods: {
    }
}
</script>

netlify で、Vue.js (Vue CLI 3) のSPAサイトの設置 SPA開発(8) #Vue.js #firebase #web #SPA

index:

概要:

前のSPA(SinglePageApplication) 関連で、
netlify.com でのデプロイ公開 の内容となります。

環境

Vue-CLI 3.6.6
Vue.js
vue-router
firebase

手順

事前にアカウントの作成しておきます。
(今回は、github アカウントで、ログイン)

https://app.netlify.com
 を開く。
・site タグ(ログインしたページ)
右上の [New Site from Git ]のボタンが表示されているページ
 を開く
=> 下側に、枠が表示され
[Want to deploy a new site ...
Drag and drop your site ...]
らしき、文字が見えますので。確認しておきます

f:id:knaka0209:20190428180220p:plain


・zipファイルの、準備
vue-CLI で、ビルドします。

npm run build

・ dist/ フォルダを、zip圧縮して
上記の、ドラッグ枠にドロップします。
 => サイト公開されます。

・ URLは、完了画面に。表示されたようです。

参考のページ

knaka0209.hatenablog.com

Update 2019/04/29

・ビルド後に、netlify
 で正常の、ページ再読込み等が動作しない場合の修正
=>vue-router で、historyモードが、build後に動作しない現象
masterブランチを更新しました。
https://github.com/kuc-arc-f/vue_2_ver2

・対応の関連
https://router.vuejs.org/ja/guide/essentials/history-mode.html

firebase / Cloud firestore の開始編、web版のデータ登録 SPA開発(7) #firebase #web #SPA

index:

概要:

前のSPA(SinglePageApplication) 関連で、firebase の設定編となります。

・接続は、Vue.jsのweb版の予定

環境

Vue-CLI 3.6.6
Vue.js
vue-router
firebase

手順

・上記等の、関連を参考に進めましたが

・プロジェクトの作成

・database は、Cloud firestore
 を、追加した場合です。

・セキュリティルールは、書込み可能
 に設定する。

・コレクションの追加
 例: tasks

・フィールドの追加、完了

接続、データ登録

・プロジェクト作成時の、JSコードや、
 config設定を使用。

・接続、データ読込み

<script>
    var items = []
    this.database = firebase.firestore()
    var dbRef = this.database.collection("tasks")
    dbRef = dbRef.orderBy("title", "desc")
    dbRef.get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
            var item = doc.data()
            /* console.log(doc) */
            items.push({
                title : item.title
            })            
        })
    })

</script>

参考のページ

knaka0209.hatenablog.com

Vue CLI 3 の準備編、 SPA開発(6) #Vue.js #web #SPA

index:

概要:

前のSPA(SinglePageApplication) 関連で、Vue CLI 3 の設定編となります。
の実装編となります。

・バックエンドは firebase予定の構成

環境

Vue-CLI 3.6.6
Vue.js
vue-router
firebase

参考の設定

github.com

v3 設定方法

・古い、v2 がある場合、消します。

npm -g uninstall vue-cli
npm install -g @vue/cli
vue create my-project
cd my-project

・サービス起動
npm run serv

http://localhost:8080 で、TOP画面が開きます

・ビルドする場合
npm run build

npm の追加、

・vue-router
 package.jsonで、追加する場合。
https://github.com/kuc-arc-f/vue_2_ver2/blob/master/package.json
 下記を、追加

	"vue-router": "^3.0.1",

npm install

・firebase を追加する場合
npm install --save firebase

・consoleを、使用する場合。
 下記の、rules を追加

    "rules": {
      "no-console": 0
    },

参考のページ

knaka0209.hatenablog.com