vue/vuex sample

by moehiko

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.min.js"></script>
<html></html>
<head></head>
<body>
<div id="contents"></div>
</body>

CSS

ul, li {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	vertical-align: baseline;
}

li {
  list-style: none;
  margin-bottom: 3px;
}

body {
  background-color: #f5f5f5;
}

#contents {
  padding: 10px;
}

#menu {
  margin-bottom: 10px;
}

.mod-ra {
  background-color: #fff;
  margin-bottom: 13px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}

.room {
  border-bottom: 1px solid #d8d8d8;
  padding: 5px;
}

.more-room-button {
  text-align: center;
}

#more-building-button {
  padding-top: 20px;
  text-align: center;
  height: 45px;
  background-color: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}

JavaScript

const store = new Vuex.Store({
  state: {
  	rooms: [
        { name: "部屋1", rent: 10000, area: 30 }, 	
        { name: "部屋2", rent: 20000, area: 20 },
        { name: "部屋3", rent: 30000, area: 10 },
        { name: "部屋4", rent: 40000, area: 10 },
    		{ name: "部屋5", rent: 50000, area: 10 }
    ],
    displayCount: 3
  },
  mutations: {
    sort (state, sortKey) {
			// このメソッド内の処理はajaxでサーバサイドで検索することになる
      // 検証のためフロントでソートを仮実装
      if (sortKey == "default" || sortKey == 'low') {
	      state.rooms.sort(function (a, b) {
  	    	return (a.rent < b.rent)? -1 : 1
    	  })	
      } else {
	      state.rooms.sort(function (a, b) {
  	    	return (a.rent > b.rent)? -1 : 1
    	  })
			}
    },
    more (state) {
    	state.displayCount = state.displayCount + 3
    }
  },
  actions: {
    sort (context) {
	  	context.commit('sort')
    },
    more (context) {
	  	context.commit('more')
    }
  }
})

const Sortmenu = {
	template: `
  	<div id="sortChanger" v-on:change="handleOnChange">
    	<select>
      	<option value="low">安い順</option>
      	<option value="high">高い順</option>
    	</select>
  	</div>`,
  methods: {
  	handleOnChange: function (event) {
    	store.dispatch('sort', event.target.value)
    }
  }
}

const Morebutton = {
	template: `
  	<div 
    	class="more-room-button" 
    	v-on:click="handleOnClicked"
    	v-show="$store.state.rooms.length >= $store.state.displayCount"  
    >部屋をもっとみる</div>`,
  methods: {
  	handleOnClicked: function (event) {
    	store.dispatch('more')
    }
  }
}

const Roomlist = {
 	props: ['name', 'rent', 'area', 'index'],
  template: `
  	<div class="room">
    	<ul>
      	<li>{{ name }}</li>
        <li>賃料: {{ rent }}</li>
        <li>面積 :{{ area}}</li>
     </ul>
  </div>`
}

const Modra = {
  components: { Roomlist, Morebutton},
  template: `
  		<div class="mod-ra">
        <roomlist
          v-for="(room, index) in $store.state.rooms"
          v-bind:name="room.name"
          v-bind:rent="room.rent"
         ...