LoginSignup
0
0

More than 3 years have passed since last update.

Nuxt.js + Vue.js + Vuex によるカウンターのサンプルコード

Last updated at Posted at 2020-03-27

概要

  • Nuxt.js + Vuex を使用して「+」「-」ボタンで数値が増減するカウンターを作成する

今回の環境

  • Node.js 13.12.0
  • Nuxt.js 2.12.1

Nuxt.js + Vuex によるカウンターのサンプルコード

ソースコード一覧

├── package.json
├── pages
│   └── counter.vue
└── store
    └── counter.js

package.json

{
  "name": "my-app",
  "dependencies": {
    "nuxt": "2.12.1"
  }
}

pages/counter.vue

<template>
  <div>
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</template>

<script>
export default {
  computed: {
    count () {
      console.log('Call the computed count')
      return this.$store.state.counter.count
    }
  },
  methods: {
    // 「+」ボタンクリック時に呼ばれる
    increment () {
      console.log('Call the methods increment')
      // mutations の increment を呼び出す
      this.$store.commit('counter/increment')
    },
    // 「-」ボタンクリック時に呼ばれる
    decrement () {
      console.log('Call the methods decrement')
      // mutations の decrement を呼び出す
      this.$store.commit('counter/decrement')
    }
  }
}
</script>

store/counter.js

// カウンターの値を管理するストア (Vuex.Store)

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

export const mutations = {
  increment (state) {
    console.log('Call the mutations increment')
    state.count++
  },
  decrement (state) {
    console.log('Call the mutations decrement')
    state.count--
  }
}

Node.js サーバを起動

package.json に記述したライブラリをインストール。

$ npm install

Node.js サーバを起動。

$ ./node_modules/nuxt/bin/nuxt.js

   ╭─────────────────────────────────────────────╮
   │                                             │
   │   Nuxt.js v2.12.1                           │
   │   Running in development mode (universal)   │
   │                                             │
   │   Listening on: http://localhost:3000/      │
   │                                             │
   ╰─────────────────────────────────────────────╯

ℹ Preparing project for development
ℹ Initial build may take a while
✔ Builder initialized
✔ Nuxt files generated

✔ Client
  Compiled successfully in 5.69s

✔ Server
  Compiled successfully in 5.30s

ℹ Waiting for file changes
ℹ Memory usage: 121 MB (RSS: 200 MB)
ℹ Listening on: http://localhost:3000/

Web ブラウザで http://localhost:3000/counter にアクセスすると「+」「-」ボタンと数値が増減するカウンターが表示される。

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0