[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>

 

 

Leave a Reply