前言
共用的狀態、方法,可以抽離出來成為 mixin,需要使用時再混入。
做法
在 mixins 資料夾新增 common.js 檔。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 
 | const common = {data() {
 return {
 capsLock: false,
 };
 },
 computed: {
 
 breakpoint() {
 return this.$vuetify.breakpoint;
 },
 },
 methods: {
 
 capitalize(word) {
 return `${word.charAt(0).toUpperCase()}${word.slice(1)}`;
 },
 setCapsLock(capsLock) {
 this.capsLock = capsLock;
 },
 
 detectCapsLock(event) {
 if (!event.getModifierState) {
 return false;
 }
 const isCapsLock = event.getModifierState('CapsLock');
 if (this.capsLock === isCapsLock) {
 return false;
 }
 return this.setCapsLock(isCapsLock);
 },
 },
 };
 
 export default common;
 
 | 
在需要使用的元件中引入 mixin,直接使用 mixin 的狀態、方法。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | <template><div>
 <v-dialog>
 <v-card>
 <v-card-text>
 <v-form>
 <v-text-field
 @keyup="detectCapsLock"
 @keydown="detectCapsLock"
 />
 </v-form>
 </v-card-text>
 </v-card>
 </v-dialog>
 </div>
 </template>
 
 import common from '@/mixins/common';
 
 export default {
 mixins: [
 common,
 ],
 };
 
 |