vue

網頁

Vue Composition API using ES module

網站沒有做前後端分離,但想要用 Vue,而且還要用 Composition API,可以使用下面的方式:

// 引用的時候記得要加上 type="module"
// <script src="demo.js" type="module"></script>
// 開發的時候可以把 vue.esm-browser.prod.js 的 .prod 去掉,方便用 Vue.js devtools 除錯

import {
  createApp,
  ref,
  computed,
  watch,
  nextTick,
  onMounted,
} from 'https://unpkg.com/vue@3/dist/vue.esm-browser.prod.js';

// 引入 component
import SelectComponent from './select-component.js';

const vueApp = createApp({
  components: {
    SelectComponent,
  },

  setup() {
    ...

    return { ... }
  }
});

vueApp.mount('#app');
// select-component.js

import { ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.prod.js';

export default {
  name: 'SelectComponent',

  props: ['modelValue', 'getPageNumber', 'itemsPerPage'],

  emits: ['update:modelValue'],

  template: `
    <select
      class="form-select"
      v-model="page"
      @change="$emit('update:modelValue', $event.target.value)"
    >
      <option
        :value="n"
        v-for="n in getPageNumber"
      >
        Episode {{ (n * itemsPerPage) - itemsPerPage + 1 }} ~ Episode {{ n * itemsPerPage }}
      </option>
    </select>
  `,

  setup(props) {
    const page = ref(props.modelValue);

    return { page };
  },
};
// 在 html 使用 component
// tag 使用 <select-component></select-component>

<select-component
  v-model="page"
  :get-page-number="getPageNumber"
  :items-per-page="ITEMS_PER_PAGE"
></select-component>
網頁

[Vue] Global State with Composables

在 Vue Composition API 下,想要有全域狀態,但又不用 Pinia,可以使用下面的方法:

// 檔名:useTest.js

import { ref, readonly } from 'vue';

// 有 import 這個檔案的 .vue 都可以使用這個 ref
const global = ref(0);

export function useTest() {
  // import 這個檔案的 .vue 檔,各自有這個 ref
  const count = ref(0);

  const countPlus = () => {
    count.value++;
  };

  const globalPlus = () => {
    global.value++;
  };

  return {
    // 設定全域 ref 唯讀,只能透過 return 的 function 修改
    global: readonly(global),
    globalPlus,
    count,
    countPlus
  };
}


參考連結:

網頁

Vue 3.4

把公司參訪報名管理頁的 Vue 升到 3.4。

Vue 3.4 可以在 Component 上使用 v-model 的時候,少寫幾行 code。

以操作畫面最上方的搜尋功能為例,原本的 code 長這樣….

<script setup>
import { computed } from 'vue';

const props = defineProps({ modelValue: String });
const emit = defineEmits(['update:modelValue']);

const searchString = computed({
  get() {
    return props.modelValue;
  },
  set(newVal) {
    emit('update:modelValue', newVal);
  }
});
</script>

現在只要這樣….

<script setup>
import { defineModel } from 'vue';

const searchString = defineModel({ type: String });
</script>

———

預設的排序是 No 欄位(由大到小),點選參訪日期也可以排序。

參訪日期一開始的排序寫法是:

// 由大到小
[...allData.value].sort((a, b) => {
  if (a['date'] > b['date']) {
    return -1;
  }

  if (b['date'] > a['date']) {
    return 1;
  }

  return 0;
}

後來看到一個比較簡潔的寫法:

// 由大到小
[...allData.value].sort((a, b) => b['date'].localeCompare(a['date']))


參考連結:

返回頂端