LoginSignup
0
1

More than 1 year has passed since last update.

Vue.js で Checkbox を Template 化する

Posted at

環境

vue.js
javascript

やりたいこと

  • Vue-Component を用いて、data-binding しつつ、選択肢としての options も Component 外部から渡したい。
  • data-binding されている値が、options に含まれているのであれば、初期選択状態にしたい。
  • 可能な限り再利用可能な汎用的な構成にしたい

結論

app.js
const vueCkeckbox = Vue.component('vue-checkbox', {
    template:`
    <div>
        <template
            v-for"(opt, idx) of options"
        >
            <div :key="idx">
                <input
                    type="ckeckbox"
                    :name="name"
                    :id="name+idx"
                    :checked="value.indexOf(opt) !== -1"
                    v-bind:value="opt"
                    v-on:change="onChange"
                />
                <label
                    :for="name+idx"
                >
                {{opt}}
                </label>
            </div>
        </template>
    </div>
    `,
    name:String,
    props:{
        value:{
            type:Array,
            default: () => {
                return [];
            }
        },
        options:{
            type:Array,
            default: () => {
                return [];
            }
        }
    },
    data(){
        return {
            values:[]
        };
    },
    methods:{
        onChange(event){
            let elem = event.target;
            let val = elem.value;

            if(elem.checked){
                this.values.push(val);
            }else{
                this.values = this.values.filter((v) => {
                    return (v !== val);
                });
            }

            //update bind value.
            this.$emit('input', this.values);
        }
    },
    created(){
        //Memory of initial selection value.
        this.values = this.value.concat(this.values);
    }
});

let app = new vue({
    el: '#app',
    components: {
        'vue-checkbox': vueCheckbox
    },
    data: {
        values: ['りんご']
    }
});

index.html
<div id="app">
    <fieldset>
        <legend>Vue-Component Checkbox Demo</legend>
        <vue-checkbox
            name="checkbox_demo"
            :options="['りんご','みかん','なし']"
            v-model="values"
        >
        </vue-checkbox>
    </fieldset>
</div>

参考

上記コードを参照の事

0
1
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
1