データを保存できるようになったので、今回はデータの取得方法と表示を見直していきます。
computedを使って状態を取得したいと思います。
computedは健作すると「計算された」などという意味が出てきます。
vue.jsのサイトでは算出プロパティと呼ばれている。
意味的にはロジックをもったプロパティで、テンプレートにロジックをゴリガリ書くのはやめましょうということです。
公式のTodoではタスクが完了しているやつ、未完了のやつ、全てのタスク、といった3パターンのタスク一覧を取得できるようになっていますが、テンプレートでは、そういったロジックは書いてなく、全てcomputedの中に入っております。
今回作るアプリケーションも今後のパンプアップを見据えてcomputedでstoreの状態を取得していきます。
その前にlist.jsの方でgettersを定義します。
これはStore内の算出プロパティらしいです。
公式のTodoでも使われているので定義しておきます
export const state = () => ({
lists: [{
name: "牛乳",
price: 160
}, {
name: "りんご",
price: 200
}]
})
//追加
export const getters = {
allLists(state) {
return state.lists
}
}
export const actions = {
addList({
commit
}, list) {
commit('ADD_LIST', list)
}
}
export const mutations = {
ADD_LIST(state, obj) {
state.lists.push({
name: obj._name,
price: obj._price
})
}
}
続いてtest.vueを修正します
<template>
<v-container>
<v-layout justify-center row>
<v-flex xs11 md10>
<div id="main-area">
<h1>超リッチな買い物リスト</h1>税率
<input type="text" placeholder="税額" value="8">
<label for="">%</label>
<v-layout justify-space-around>
<v-flex xs6 md5>
<v-text-field label="商品名" v-model="name" required ></v-text-field>
</v-flex>
<v-flex xs6 md5>
<v-text-field label="値段" v-model="price" required ></v-text-field>
</v-flex>
</v-layout>
<v-layout justify-space-around>
<v-flex xs10>
<v-btn block color="secondary" @click='add' dark>ADD</v-btn>
</v-flex>
</v-layout>
<div id="list-area">
<ul>
<li v-for="list in lists" v-bind:key="list.id">{{list.name}}{{list.price}}円 </li>
</ul>
</div>税込9999円 税抜8888円
</div>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
export default {
layout: 'mylayout',
data(){
return {
name:'',
price:''
}
},
//状態を変更する
methods:{
add:function(){
if(this.name != '' && this.price != ''){
this.$store.dispatch(`list/addList`,{_name:this.name,_price:this.price})
this.name = ''
this.price = ''
}
}
},
//状態を取得する
computed: {
lists(){
return this.$store.getters['list/allLists']
}
}
}
</script>
computedでstoreのgettersにアクセスしてリストを取得しています。
<li v-for="list in lists" v-bind:key="list.id">{{list.name}}{{list.price}}円 </li>
またli要素にv-forを使っています。listsの中身を走査して一つずつ取り出してくれます。
コメント