【Rpi】Themal Camera

mlx90640-library
https://github.com/pimoroni/mlx90640-library

sudo apt-get update
sudo apt-get install libi2c-dev
sudo apt-get install libavutil-dev
sudo apt-get install libavcodec-dev
sudo apt-get install libavformat-dev
sudo apt install libsdl2-dev

\boot/config.txt
dtparam=i2c1_baudrate=1000000

make clean
make bcm2835
make I2C_MODE=LINUX

【Android】カスタムURL

ブラウザなどからアプリを立ち上げる

AndroidManifest.xml

<activity
android:name=".HomeActivity"
android:screenOrientation="portrait"
android:hardwareAccelerated="true"
android:launchMode="singleTop"> <intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="mknod" android:host="test"/>
</intent-filter>

 

intent送信

adb shell am start -a android.intent.action.VIEW -d "mknod://test" jp.mknod.app_packagename

 

 

【djnago】create API project

install 

install python3
pip install django pip install djangorestframework pip install django-filter

create

django-admin startproject (project)
cd (project)
django-admin startapp (app)

cd (app)

create urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url('', views.index, name='index'),
]

 

views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse('<h1>Hello, myapp1!</h1>')

 

cd (project)

modify urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [

path('admin/', admin.site.urls),
url('api/', include('api.urls')),
]
INSTALLED_APPS = [

'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
]

 

python manage.py makemigrations
python manage.py migrate

 

(app)/adimn.py

from django.contrib import admin

# Register your models here.
from .models import Staff
from .models import TimeCard
from .models import Record
admin.site.register(Staff)
admin.site.register(TimeCard)
admin.site.register(Record)

 

【raspberry】python 3.7

python3.7をインストール
sudo apt-get install build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev
wget https://www.python.org/ftp/python/3.7.4/Python-3.7.4.tar.xz
tar xf Python-3.7.4.tar.xz
cd Python-3.7.4
./configure
make
sudo make altinstall
sudo apt-get install python3-distutils
curl
https://bootstrap.pypa.io/get-pip.py -o get-pip.py pip --version

 

[Nuxt.js/TS] Store モジュール分割

store/Book/index.ts

export interface Book {
  title: string
  text: string
}

export const state = () => (
{
  books: [{ title:"title1",text:"abc" }]
})

export const mutations = {

  add (state, book: Book) {
    state.books.push(book)
  },
  all (state): Book[] {
    return state.books
  },

}

store/index.ts

export const state = () => ({
  counter: 0
})

export const mutations = {
  increment (state) {
    state.counter++
  },
 }

export const actions = {

  action_inc ( {commit} ) {
    commit('increment')
  },  
 

pages/todo.vue

<template>
<div>
  <ul>
    <!-- <li v-for="t in $store.state.Book.books"> -->
    <li v-for="t in books">
      <span>{{ t.title }}</span>
    </li>
  </ul>
  <button @click="add_book">ADD</button>
</div> 
</template>

<script lang="ts">

// TS VER.
  import { Component, Vue, namespace } from 'nuxt-property-decorator'
//  import { Vue, Component, namespace } from 'vue-property-decorator'
  import { mapMutations, mapActions  } from 'vuex'

  const StoreBook = namespace('Book')

  @Component({
  })

  export default class extends Vue {

    @StoreBook.Mutation add
    @StoreBook.Mutation all

    //------------------------------------------
    // getter
    //------------------------------------------
    private get cnt(): number {
      return this.$store.state.counter
    }

    private get books():[] {
      return this.$store.state.Book.books
    }

    //------------------------------------------
    // mutation
    //------------------------------------------
    clicked_inc(): void{
      this.$store.commit('increment')
    }

    //------------------------------------------
    // action
    //------------------------------------------

    get_books():Object[]{
      console.log("get_books" )
      return this.all();
    }
    add_book(el): void{
      var b = { title:"title1",text:"abc" }
      this.add(b)
    }
  }
</script>

<style>
.done {
  text-decoration: line-through;
}


</style>

 

 

[Nuxt.js/TS] Store

Vuex

https://vuex.vuejs.org/ja/guide/actions.html

Storeフォルダにデータ管理機能を作る

 

state

mutation

action

module(別記事)

 

<template>
<div>
  <p >{{$store.state.counter}}</p>
  <p @click="clicked_inc">increment: {{cnt}}</p>
  <p @click="clicked_inc_n(2)">increment_n: {{cnt}}</p>
  <p @click="clicked_inc_payload">increment_payload: {{cnt}}</p>  
  <p @click="clicked_inc_obj">increment_obj: {{cnt}}</p>  
  <p @click="inc_method">inc_method: {{cnt}}</p>

  <p @click="clicked_inc_action">increment action: {{cnt}}</p>  
  <p @click="clicked_inc_action_async">increment action Async: {{cnt}}</p>  

  <p @click="clicked_inc_action">action_inc_method: {{cnt}}</p>
  <p @click="clicked_inc_action_async">action_inc_async_method: {{cnt}}</p>
  <p @click="inc_action_async_method">action_inc_async_method: {{cnt}}</p>
  <p @click="action_inc_payload(5)">inc_action_payload: {{cnt}}</p>
  <p @click="clicked_actionA_async">clicked_actionA_async: {{cnt}}</p>

  <ul>
    <!-- <li v-for="t in $store.state.Book.books"> -->
    <li v-for="t in books">
      <span>{{ t.title }}</span>
    </li>
  </ul>
  <button @click="add_book">ADD</button>
  <!--
  <ul>
    <li v-for="todo in todos">
      <input type="checkbox" :checked="todo.done" @change="toggle(todo)">
      <span :class="{ done: todo.done }">{{ todo.text }}</span>
    </li>
    <li><input placeholder="What needs to be done?" @keyup.enter="addTodo"></li>
  </ul>
  -->

 </div> 
</template>

<!-- JS VERSION
<script>
  import { mapMutations } from 'vuex'

  export default {
    computed: {
      todos () {
        return this.$store.state.todos.list
      }
    },
    methods: {
      addTodo (e) {
        this.$store.commit('todos/add', e.target.value)
        e.target.value = ''
      },
      ...mapMutations({
        toggle: 'todos/toggle'
      })
    }
  }
</script>
-->

<script lang="ts">

// TS VER.
  import { Component, Vue, namespace } from 'nuxt-property-decorator'
//  import { Vue, Component, namespace } from 'vue-property-decorator'
  import { mapMutations, mapActions  } from 'vuex'

  const StoreBook = namespace('Book')

  @Component({
    methods: {
      ...mapMutations({ toggle: 'toggle' }),
      ...mapMutations({ inc_method: 'increment' }),

      ...mapActions( {inc_action_async_method: 'action_inc_async'} ), // `this.add()` を `this.$store.dispatch('increment')` にマッピングする]
      ...mapActions( ['action_inc_payload', ]), // `this.add()` を `this.$store.dispatch('increment')` にマッピングする]
    }
  })

  export default class extends Vue {

    @StoreBook.Mutation add
    @StoreBook.Mutation all

    //------------------------------------------
    // getter
    //------------------------------------------
    private get cnt(): number {
      return this.$store.state.counter
    }

    private get books():[] {
      return this.$store.state.Book.books
    }

    //------------------------------------------
    // mutation
    //------------------------------------------
    clicked_inc(): void{
      this.$store.commit('increment')
    }

    clicked_inc_n(n): void{
      this.$store.commit('increment_n', n)
    }

    clicked_inc_payload(): void{
      this.$store.commit('increment_payload', {amount: 3} )
    }

    clicked_inc_obj(): void{
      this.$store.commit( {type:'increment_payload', amount: 4} )
    }
    //------------------------------------------
    // action
    //------------------------------------------
    clicked_inc_action(): void{
      this.$store.dispatch('action_inc')
    }
    clicked_inc_action_async(): void{
      this.$store.dispatch('action_inc_async')
    }

    //非同期処理ー成功処理実装
    //clicked_actionA_async(): void{
      // this.$store.dispatch('actionA').then(()=>{
      //   console.log("finished")
      // })
    //}

    // 非同期処理ー成功、失敗処理実装
    // clicked_actionA_async(): void{
    //   this.$store.dispatch('actionA').then(()=>{
    //     console.log("success")
    //   },
    //   ()=>{
    //     console.log("error")
    //   })
    // }

    // 非同期処理ーCallback分けた場合
    successCallback(): void {
      console.log("It succeeded with " )
    }

    failureCallback(): void {
      console.log("It failed with " )
    }
    clicked_actionA_async(): void{
      this.$store.dispatch('actionA').then(
        this.successCallback,
        this.failureCallback)
    }

    // private get todos(): Object {
    //   return this.$store.state.todos.list
    // }

    get_books():Object[]{
      console.log("get_books" )
      return this.all();
    }
    add_book(el): void{
      var b = { title:"title1",text:"abc" }
      this.add(b)
    }

    addTodo(e): void {
      this.$store.commit('add', e.target.value)
      e.target.value = ''
    }
  }
</script>

<style>
.done {
  text-decoration: line-through;
}


</style>

 

store/index.ts

export const state = () => ({
  counter: 0
})

export const mutations = {
  increment (state) {
    state.counter++
  },
  increment_n (state, n) {
    state.counter += n
  },
  increment_payload (state, payload) {
    state.counter += payload.amount
  }
}

export const actions = {

  // action_inc (context) {
  //   context.commit('increment')
  // }
  // 上に同じ
  // action_inc ( {commit} ) {
  //   commit('increment')
  // },  

  action_inc ( {commit} ) {
    commit('increment')
  },  
  action_inc_payload ( {commit} ,payload) {
    commit('increment_n',payload)
  },  
  async action_inc_async( {commit} ) {
    setTimeout(() => {
      commit('increment')
    }, 2000)
  },
  actionA( {commit} ){

    //Promiseを戻せる。
    return new Promise((resolve,reject)=>{
      setTimeout(() => {
        commit('increment')

        // 成功
        resolve()

        // 失敗
        // reject()
      }, 2000)
    });
  },

}

store/Book/index.ts

 

[vue.js/nuxt.js/ts]GET axios

axiosでHttp GET

Home.vue

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <button @click = 'clicked'>"GET"</button>
    <hr>
    <p class="cmn">{{ resp_data }}</p>

</div>
</template>

<script lang="ts">
    import { Component, Watch, Vue } from 'vue-property-decorator';
    import axios from "axios";

    @Component({
        components: {
        },
    })
    export default class Home extends Vue {

        public resp_data?: string = "no data.";
        private http;
        
        public created(){
            console.log("[created]")
            this.http = axios.create();
        }

        public clicked(){
            console.log("[clicked]")
            this.get_fb().then();
        }

        public async get_fb() {

            const res = await this.http.get("https://xxxxxxxx.firebaseio.com/person.json");
            console.log(res.data);
            this.resp_data = res.data;

            return res;
        }
    }
</script>

<style>
    .cmn {
        margin: 10px;
    }
</style>

 

APIをComponentで分けた場合(APIボタンモジュール)

Pages/New.vue

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <API class="cmn" @emit_clicked='cb_clicked' caption="API"></API>
    <hr>
    <p class="cmn">RESPONSE</p>
    <p class="cmn">{{ resp_data }}</p>

</div>
</template>

<script lang="ts">
    import { Component, Watch, Vue } from 'vue-property-decorator';
    import API from "@/components/API.vue";

    @Component({
        components: {
            API,
        },
    })
    
    export default class New extends Vue {

        private resp_data?:string="";

        public cb_clicked(s:string){
            console.log("[cb_clicked]")
            console.log(s);
            
            this.resp_data=s;
        }    
    }
</script>

<style>
    .cmn {
        margin: 10px;
    }
</style>

 

API.vue

<template>
    <button @click="onClick">{{caption}}</button>
</template>

<script lang="ts">
    import {Component, Prop, Emit, Vue} from "vue-property-decorator"
    import axios from "axios";

    @Component
    export default class API extends Vue {

        private http;
        public resp_data?: string = "no data.";

        @Prop()
        public caption?: string;  

        // 上位にイベント通知
        @Emit()
        public emit_clicked(string){
        }

        public created(){
            console.log("[API]created()")
            this.http = axios.create();
        }
        
        public onClick(){
            this.get_person();
        }

        public async get_person() {

            console.log("[API]get_fb()")
            
            const res = await this.http.get("https://xxxxxxxx.firebaseio.com/person.json");
            console.log(res.data);
            this.resp_data = res.data;
 
            this.emit_clicked(res.data);
            return res;
        }

    }
</script>

 

 

[vue.js/nuxt.js/ts]Nuxt.js+TS

Nuxtjsで、プロジェクト作成
npx create-nuxt-app nuxt_ts

 

インストール
npm i -D @nuxt/typescript
npm i ts-node
npm i -S vue-property-decorator

npm i -S nuxt-property-decorator

 

js->tsに拡張子変更
nuxt.config.js -> nuxt.config.ts

 

空のファイルを作成
touch tsconfig.json

 

実行
cd nuxt_ts
npm run dev


・component作成
components/MyButton.vue

<template>
    <button>My Button</button>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator"

    @Component
    export default class MyButton extends Vue{
        
    }
</script>

 

・Page作成
pages/Home.vue

<template>
    <div>
        <MyButton></MyButton>
    </div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import MyButton from "@/components/MyButton.vue";

    @Component({
        components: {
            MyButton,
    },
    })
    export default class Home extends Vue {}
</script>

<style>
</style>

 

 

@prop @emitプロパティ/バインド・イベント

components/MyButton.vue

<template>
    <button @click="onClick">{{ title }}</button>
</template>

<script lang="ts">
    import {Component, Prop, Emit, Vue} from "vue-property-decorator"

    @Component
    export default class MyButton extends Vue {

        public title?: string="HELLO";   // ?: 初期化されてない !:初期化されている

        @Prop()
        public caption?: string;  

        // バインドしている側にイベント通知
        @Emit()
        public clicked(){
        }

        public onClick(){
            
            //自分のメンバ変数を変更 -> OK
            this.title = "clicked";

//            alert(this.caption);
            // !!! バインドされたプロパティを変更するとエラー
            //this.caption = "clicked";
            
            // バインドしている側にイベント通知して、そこで変える。
            this.clicked();
        }
    }
</script>

pages/Home.vue

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <p>opt: {{opt}}</p>
    <MyButton v-bind:caption="opt" @clicked='cb_clicked'></MyButton>
</div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import MyButton from "@/components/MyButton.vue";

    @Component({
        components: {
            MyButton,
        },
    })
    export default class Home extends Vue {

        public opt: string = "INITIALIZED";

        public cb_clicked(){
            this.opt = "[CALLBACK]CLICKED";
            console.log(this.opt);
        }
    }
</script>

<style>
</style>

 

v-model モデルバインド

アクションごとに、バインドされている変数が変更される。

ResetButton.vue

<template>
    <button @click="onClick">Reset</button>
</template>

<script lang="ts">
    import {Component, Emit, Prop, Vue} from "vue-property-decorator";

    @Component
    export default class ResetButton extends Vue {
        @Prop()
        public initialValue!: string;

        /** モデルバインドのために記述必須 */
        @Prop()
        public value!: string;

        /** モデルバインドのために記述必須 */
        @Emit()
        public input(value: string) {
        }

        public onClick(){
            this.input(this.initialValue);
        }
    }
</script>

Home.vue

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <p>opt: {{opt}}</p>

    <!-- プロパティ・イベントをバインド -->
    <MyButton v-bind:caption="opt" @clicked='cb_clicked'></MyButton>

    <!-- モデルバインド -->
    <ResetButton initialValue="Hello" v-model="opt"></ResetButton>
</div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import MyButton from "@/components/MyButton.vue";
    import ResetButton from "@/components/ResetButton.vue";

    @Component({
        components: {
            MyButton,
            ResetButton,
        },
    })
    export default class Home extends Vue {

        public opt: string = "INITIALIZED";

        public cb_clicked(){
            this.opt = "[CALLBACK]CLICKED";
            console.log(this.opt);
        }
    }
</script>

<style>
</style>

 

フックルーチン(created)

ResetButton.vue

<template>
    <button @click="onClick">Reset</button>
</template>

<script lang="ts">
    import {Component, Emit, Prop, Vue} from "vue-property-decorator";

    @Component
    export default class ResetButton extends Vue {

        public initialValue!: string;

        @Prop()
        public value!: string;

        public created(){
            console.log("[created]")
            this.initialValue = "init value"
        }

        @Emit()
        public input(value: string) {
        }

        public onClick(){
            this.input(this.initialValue);
        }
    }
</script>

 

Home.vue

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <p>opt: {{opt}}</p>

    <!-- プロパティ・イベントをバインド -->
    <MyButton v-bind:caption="opt" @clicked='cb_clicked'></MyButton>

    <!-- モデルバインド -->
    <ResetButton v-model="opt"></ResetButton>
</div>
</template>

 

算出プロパティ(vueだと、computed)

<template>
<!-- ルートエレメントが1個必要 !!! -->
<div>   
    <p>opt: {{opt}}</p>
    <p>cnt: {{count}}</p>
    <p v-if="isRegulars">いつもありがとうございます</p>

    <!-- プロパティ・イベントをバインド -->
    <MyButton v-bind:caption="opt" @clicked='cb_clicked'></MyButton>

    <!-- モデルバインド -->
    <ResetButton v-model="opt"></ResetButton>
</div>
</template>

<script lang="ts">
    import { Component, Vue } from 'vue-property-decorator';
    import MyButton from "@/components/MyButton.vue";
    import ResetButton from "@/components/ResetButton.vue";

    @Component({
        components: {
            MyButton,
            ResetButton,
        },
    })
    export default class Home extends Vue {
        
        private count: number = 0;
        public opt: string = "INITIALIZED";

        public get isRegulars(): boolean{
           return this.count >= 5;
        }

        public cb_clicked(){
            this.opt = "[CALLBACK]CLICKED";
            console.log(this.opt);
            this.count++;
        }
    }
</script>

<style>
</style>

 

Watch

値変更を監視し、処理を追加する

<script lang="ts">
    import { Component, Watch, Vue } from 'vue-property-decorator';
    import MyButton from "@/components/MyButton.vue";
    import ResetButton from "@/components/ResetButton.vue";

    @Component({
        components: {
            MyButton,
            ResetButton,
        },
    })
    export default class Home extends Vue {
        
        private count: number = 0;
        public opt: string = "INITIALIZED";

        public get isRegulars(): boolean{
           return this.count >= 5;
        }

        @Watch('count')
        public countChanged(){
            if(this.count === 5){
                alert("count == 5");
            }
        }

        public cb_clicked(){
            this.opt = "[CALLBACK]CLICKED";
            console.log(this.opt);
            this.count++;
        }
    }
</script>

 

 

 

[ts]デコレーター

デコレーター

関数や、変数にアクセスするとき、前処理を挿入できる。

 

compileすると、.jsファイルができる。

tsc –target ES5 –experimentalDecorators deco.ts

 

deco.ts


//1. デコレーターファクトリー
function deco() {
    console.log("deco(): evaluated");
    return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
        console.log("deco(): called");
    }
}

class A{
    @deco()
    greeter(person:string) {
        return "Hello, " + person;
    }
}


// メソッドデコレーター
function method_deco(target, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("method_deco(): called");
}

// クラスデコレーター
function class_deco(fnc: Function){
    console.log("class_deco(): called");
}

// パラメーターデコレーター
function param_deco(target: any, props: string, index: number) {
    console.log("param_deco(): called");
}

@class_deco
class B{
    
    @method_deco
    hoge(@param_deco person:string) {
        return "Hello, " + person;
    }
}


let user = "yamada taro";

let a = new A();
let b =new B();

document.body.innerHTML = a.greeter(user);
document.body.innerHTML += b.hoge(user);

 

test.html

<!DOCTYPE html>
<html>
    <head><title>TypeScript Greeter</title></head>
    <body>
        <!-- <script src="greeter.js"></script> -->
        <!-- <script src="class.js"></script> -->
        <script src="deco.js"></script>
    </body>
</html>

 

デコレーターの呼ばれる順番

deco(): evaluated
deco(): called
param_deco(): called
method_deco(): called
class_deco(): called

 

[js]Typescript

typescript

https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html

 

setup

setup
npm install -g typescript

file (.ts)
xxx.ts

compile to .js
tsc  xxx.ts

 

sample
 
greeter.js
function greeter(person) {
return"Hello, "+person;
}
var user = "Jane User";
//# warning
//let user = [ "Jane User","b","c"];
document.body.innerHTML = greeter(user);

interface/class

class Student {
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

// #interface
//let user = { firstName: "Jane", lastName: "User" };

// #class
let user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);

 

[Vue.js/Nuxt.js]

Nuxt.js

・create project
npx create-nuxt-app (nuxt_app)

・To getting started:
cd nuxt_app
npm run dev

・To build & start for production:
cd nuxt_app
npm run build
npm start

folder

pages  —- index.vue
layouts —- default.vue
components —- Logo.vue

[Vue.js/Nuxt.js]非同期通信

axio.get(“http:xxx/”).then((res)=>{  処理  });

 

json_test_async.vue

<template>
  <div class="container">
    <div>
      <!-- <logo /> -->
      <div class="title">
        {{ title }}
      </div>
      <div class="subtitle">
        {{ msg }}
      </div>
      <button @click="get_json_click">get json</button>

      <p class="html_data">
        {{json_data}}
      </p>

      <table>
        <tr>
          <th>user id</th>
          <td>{{json_data.userId}}</td>
        </tr>
        <tr>
          <th>id</th>
          <td>{{json_data.id}}</td>
        </tr>
        <tr>
          <th>title</th>
          <td>{{json_data.title}}</td>
        </tr>
        <tr>
          <th>body</th>
          <td>{{json_data.body}}</td>
        </tr>        
      </table>

    </div>
  </div>
</template>

<script>
const axios = require('axios');
let url = "https://jsonplaceholder.typicode.com/posts/1";

export default {
  data: function(){
    return {
      title:'AXIOS',
      msg: 'GET JSON',
      json_data: {},
    };
  },
  methods:{
    get_json_click: function(event){
      axios.get(url)
      .then( (ret)=>{
        this.json_data = ret.data;
      })
      .catch((error)=>{
        this.msg = 'ERROR';
      });
    }
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 20px;
  color: #35495e;
  letter-spacing: 1px;
  padding-bottom: 5px;
}

.subtitle {
  font-weight: 300;
  font-size: 14px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

 

 

 

[vue.js/Nuxt.js]JSON Parse

 

json_test.vue

<template>
  <div class="container">
    <div>
      <!-- <logo /> -->
      <div class="title">
        {{ title }}
      </div>
      <div class="subtitle">
        {{ msg }}
      </div>
      <p class="html_data">
        {{json_data}}
      </p>

      <table>
        <tr>
          <th>user id</th>
          <td>{{json_data.userId}}</td>
        </tr>
        <tr>
          <th>id</th>
          <td>{{json_data.id}}</td>
        </tr>
        <tr>
          <th>title</th>
          <td>{{json_data.title}}</td>
        </tr>
        <tr>
          <th>body</th>
          <td>{{json_data.body}}</td>
        </tr>        
      </table>

    </div>
  </div>
</template>

<script>
const axios = require('axios');
let url = "https://jsonplaceholder.typicode.com/posts/1";

export default {
  data: function(){
    return {
      title:'AXIOS',
      msg: 'GET JSON',
    };
  },
  asyncData: async function(){
    let ret = await axios.get(url);
    return { json_data: ret.data };
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 20px;
  color: #35495e;
  letter-spacing: 1px;
  padding-bottom: 5px;
}

.subtitle {
  font-weight: 300;
  font-size: 14px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

 

 

[vue.js/Nuxt.js]GET/POST

create project & run

npx create-nuxt-app api_test

cd api_test
npm run dev

install axios

npm install --save axios

index.vue

<template>
  <div class="container">
    <div>
      <!-- <logo /> -->
      <div class="title">
        {{ title }}
      </div>
      <div class="subtitle">
        {{ msg }}
      </div>
      <p class="html_data">
        {{html_data}}
      </p>
    </div>
  </div>
</template>

<script>

const axios = require('axios');
let url = "/README.md";

export default {
  data: function(){
    return {
      title:'AXIOS',
      msg: 'GET SAMPLE'
    };
  },
  asyncData: async function(){
    let ret = await axios.get(url);
    return { html_data: ret.data };
  }
}
</script>

<style>
.container {
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 20px;
  color: #35495e;
  letter-spacing: 1px;
  padding-bottom: 5px;
}

.subtitle {
  font-weight: 300;
  font-size: 14px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

 

※staticフォルダは /README.mdのようにアクセスできる

 

[vue.js]store データ保存

pages/index.vue

<template>
  <div class="container">
    <h2>{{ title }}</h2>
    <p>{{ msg }}</p>

    <!-- route link -->
    <hr>
    <router-link to="/other">go to other page</router-link>
    <pre>[{{now}}]</pre>

    <!-- store deprecated from Nuxt3 -->
    <hr>
    <p>get store</p>
    <p>{{$store.state.message}}</p>
    <br>
    <p>store.cnt = {{$store.state.cnt}}</p>
    
    <p>[store]</p>
    <button v-on:click="doClick">count++</button>

    <!-- mutation -->
    <hr>
    <p>[mutation] count up </p>
    <!-- <button @click="$store.commit('count_up')">count up.</button>   -->
    <!-- <button v-on:click="doCountUp">count up.</button>   -->
    <!-- <button @click="doCountUp">count up.</button>   -->
    <button 
      @click.right.prevent="$store.commit('count_n_plus',1)"
      @click.left="$store.commit('count_n_plus',2)">
      count N up.
    </button>  

    <p>[mutation] clear count </p>
    <button v-on:click="doCountClear">count clear.</button>  
    <!-- <button @click="doCountClear">count clear.</button> -->

    <p>[mutation] set object </p>
    <button @click="$store.commit({type:'set_obj',message:'new message!',num:1})">set object</button>


    <!-- actions -->
    <hr>
    <p>[actions] actions </p>
    <button @click="$store.dispatch('do_action')">call run_action</button>

  </div>
</template>

<script>
import Logo from '~/components/Logo.vue'

export default {
  components: {
    Logo,
  },
  created: function(){
    setInterval( ()=>{
      var d = new Date();
      this.now = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
    }, 1000);
  },
  data:function(){
    return {
      title: 'Hello',
      msg: 'this is msg',
      now: 'waiting...',
    };
  },
  methods: {
    doClick: function(){
      console.log('doClick');
      this.$store.state.cnt++;
    },
    doCountUp: function(){
      this.$store.commit('count_up')
    },
    doCountClear: function(){
      this.$store.commit('count_clear')
    }
  }
};
</script>

<style>
p{
  padding:5px;
}
pre{
  padding:5px;
}
.container {
  margin: 0 auto;
  padding:40px;
  /* min-height: 100vh;
  justify-content: center;
  align-items: center;
  text-align: center; 
  display: flex; */
}

.title {
  font-family: 'Quicksand', 'Source Sans Pro', -apple-system, BlinkMacSystemFont,
    'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  display: block;
  font-weight: 300;
  font-size: 100px;
  color: #35495e;
  letter-spacing: 1px;
}

.subtitle {
  font-weight: 300;
  font-size: 42px;
  color: #526488;
  word-spacing: 5px;
  padding-bottom: 15px;
}

.links {
  padding-top: 15px;
}
</style>

 

[vue.js] componentの親子間データやり取り

子HelloWirld.vue => 親App.vue

子のプロパティーにバインドして、値を渡す。

App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"
v-bind:change_from_app="message"
v-on:result-event="appAction"
/>
<hr>
<button v-on:click="doAction">change title</button>
<p>{{ result }}</p>

</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
name: 'app',
components: {
HelloWorld
},
data: function(){
return{
message:'HELLO',
result:'no event',
}
},
methods:{
doAction: function(){
var _in = prompt("new title");
this.message = _in;
},
appAction: function(_msg){
this.result = '(*** you send: )' + _msg + ' ***)';
}
}
}
</script>
HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>{{ tx_msg }}</p>
<p>{{ change_from_app }}</p>

<div>
<input type="text" v-model="tx_input" >
<button v-on:click="doClicked">click</button>
</div>

</div>
</template>

<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
change_from_app: String
},
data: function(){
return {
tx_msg: 'what\'s your name?',
tx_input: 'no name',
};
},
methods: {
doClicked: function(){
this.tx_msg = 'hello '+ this.tx_input;

//send msg to App component.
this.$emit('result-event', this.tx_input);
},
}
}
</script>

親App.vue=>子HelloWirld.vue 
HelloWirld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>{{ tx_msg }}</p>
<p>{{ change_from_app }}</p>

<div>
<input type="text" v-model="tx_input" >
<button v-on:click="doClicked">click</button>
</div>

</div>
</template>

<script>
export default {
name: 'HelloWorld',
props: {
msg: String,
change_from_app: String
},
data: function(){
return {
tx_msg: 'what\'s your name?',
tx_input: 'no name',
};
},
methods: {
doClicked: function(){
this.tx_msg = 'hello '+ this.tx_input;

//send msg to App component.
this.$emit('result-event', this.tx_input);
},
}
}
</script>

App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"
v-bind:change_from_app="message"
v-on:result-event="appAction"
/>
<hr>
<button v-on:click="doAction">change title</button>
<p>{{ result }}</p>

</div>
</template>

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

export default {
name: 'app',
components: {
HelloWorld
},
data: function(){
return{
message:'HELLO',
result:'no event',
}
},
methods:{
doAction: function(){
var _in = prompt("new title");
this.message = _in; // set message, binded change_from_app property changed.
},
appAction: function(_msg){
this.result = '(*** you send: )' + _msg + ' ***)';
}
}
}
</script>