[VueJS] Chia components nâng cao với VueX

Trong lúc bạn làm dự án ắt hẳn bạn có nhu cầu tạo 1 form và chia components theo phân cấp như sau

  • Cart
    • Cart-Items
      • Textbox

Việc chia components như vậy sẽ giúp mình tái sử dụng được components tốt hơn. Có thể sử dụng được ở nhiều nơi.

1. Tạo BaseTextbox.vue

<!-- src/components/atoms/BaseTextbox.vue -->
<template>
  <input
    v-bind:value="value"
    v-on:input="$emit('input', $event.target.value)"
  />
</template>
<script>
export default {
  props: ['value'],
}
</script>

2. Tạo page CartView.vue

<!-- src/views/CartView.vue -->
<template>
  <div class="home">
    <cart-table :form="form" />
  </div>
</template>

<script>
// @ is an alias to /src
import { mapState } from 'vuex'
import CartTable from '@/components/molecules/CartTable.vue'

export default {
  name: 'HomeView',
  components: {
    CartTable,
  },
  computed: {
    ...mapState({
      form: 'form',
    }),
  },
  provide() {
    return {
      form: this.form,
    }
  },
}
</script>

3. Tạo CartItems.vue

<!-- src/components/molecules/CartItems.vue -->
<template>
  <div>
    <div>
      <h1>Cart Items</h1>
    </div>
    <div>
      <table>
        <tr>
          <td colspan="3">
            <base-button :value="'Refresh'" />
          </td>
        </tr>
        <tr>
          <td>1</td>
          <td>Name</td>
          <td>
            <base-textbox v-model="form.name" />
          </td>
        </tr>
        <tr>
          <td colspan="3"></td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
import BaseTextbox from '@/components/atoms/BaseTextbox.vue'
import BaseButton from '@/components/atoms/BaseButton.vue'
export default {
  components: {
    BaseTextbox,
    BaseButton,
  },
  inject: ['form'],
}
</script>

4. Tạo Store

// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    form: { name: 'aaaaaaaaaa' },
  },
  getters: {},
  mutations: {},
  actions: {},
  modules: {},
})

Chúc các bạn code vui.

F G+ T

tuandph

Khởi đầu với .NET từ năm 2013 đến nay. Hiện tại mình đang làm full-stack developer. Yêu thích lập trình & chia sẽ kiến thức. Thời gian rảnh thường làm những tool vui vui và viết lách kể lệ sự đời.