LoginSignup
0
0

More than 1 year has passed since last update.

Vue.jsでの複数checkboxの状態管理

Last updated at Posted at 2020-07-02

vueのチェックボックス管理はクセがありますよね。
例えば複数のメッセージをそれぞれチェックボックスで表示非表示制御するコンポーネントを作るとします。


<module :params="{1:{name:'ほげ', is_checked:true}, 2:{name:'はげ', is_checked:false}}"></module>
module.vue

<template>
<div>
    <div v-for="(param, index) in params" :key="'key_'+index">
        <div>
            <label>
                <input 
                    type="checkbox" 
                    :name="'checkbox['+index+']" 
                    v-model="conditions[index]">
                <span>{{ param.name }}</span>
            </label>
        </div>
        <div v-if="conditions[index]">
            お前が{{ param.name }}を覗き込む時{{ param.name }}もまたお前を覗いているのだ
        </div>
    </div>
</div>
</template>

<script>
export default {
    props: ['params'],
    data() {
        return {
            conditions:{}
        }
    },
    created: function() {
        Object.keys(this.params).forEach(index => {
            this.conditions[index] = this.params[index].is_checked;
        }
    }
</script>

以上のようにチェックボックス状態管理配列conditions[index]のbool型でチェックボックスのonoffとメッセージの表示v-ifを制御しようとしてもうまく動きません。

vueは複数チェックボックスのonoff管理をv-modelで指定する配列に該当のvalueが含まれるかどうかでやりますので

module.vue

<template>
<div>
    <div v-for="(param, index) in params" :key="'key_'+index">
        <div>
            <label>
                <input 
                    type="checkbox" 
                    :name="'checkbox['+index+']" 
                    :value="index" 
                    v-model="conditions">
                <span>{{ param.name }}</span>
            </label>
        </div>
        <div v-if="conditions.includes(index)">
            お前が{{ param.name }}を覗き込む時{{ param.name }}もまたお前を覗いているのだ
        </div>
    </div>
</div>
</template>

<script>
export default {
    props: ['params'],
    data() {
        return {
            conditions:[]
        }
    },
    created: function() {
        Object.keys(this.params).forEach(index => {
            if(this.params[index].is_checked){
                this.conditions.push(index);
            }
        }
    }
</script>

としてやると動くと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0