やりたいこと
定数ファイルに定義した内容を画面上のプルダウンに設定する
動作環境
- Vuetify 2.6.14
- Node 16.13.0
- vue 2.7.14
方法
実装
constants.js
export const fruits = {
fruit: [
{
name: 'りんご',
value: 'apple',
},
{
name: 'いちご',
value: 'strawberry',
},
{
name: 'みかん',
value: 'orange',
},
],
}
export default (context, inject) => {
inject('fruits', fruits)
}
form.vue
<template>
<v-app>
<v-container>
<v-select
v-model="selectFruit"
item-text="name"
item-value="value"
:items="dispFruits"
label="好きなくだもの"
>
</v-select>
</v-container>
</v-app>
</template>
<script>
// 定数ファイルのインポート
import { fruits } from '~/plugins/constants'
export default {
data() {
return {
// プルダウンで選択した要素の受け取り用オブジェクト
selectFruit: { name: '', value: '' },
// プルダウン表示用オブジェクト
dispFruits: null,
}
},
created() {
// プルダウン表示用オブジェクトに定数ファイルから取得したオブジェクトを追加
this.dispFruits = fruits.fruit
},
}
</script>