M
M
Maxim2021-01-29 10:33:27
Vue.js
Maxim, 2021-01-29 10:33:27

How to pass model to custom switch Vue js?

there is a switch component

<template>
  <div
    class="ivu-switch"
    :class="{ 'ivu-switch-checked': isChecked }"
    @click.prevent="toggleSwitch"
  ></div>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false,
    }
  },
  methods: {
    toggleSwitch() {
      this.isChecked = !this.isChecked
      this.$emit('input', this.isChecked)
    },
  },
}
</script>

on the form I call this component, but the question is how to pass the model to the component so that the value of isChecked changes depending on the value of the model

<InputSwitch v-model="form.is_published" />

data() {
    return {
      form: {
        is_published: false,
      },
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-01-29
@Aslero

  1. Put away:
    data() {
      return {
        isChecked: false,
      }
    },
    methods: {
      toggleSwitch() {
        this.isChecked = !this.isChecked
        this.$emit('input', this.isChecked)
      },
    },

  2. Add:
    props: {
      value: Boolean,
    },

  3. Replace: on with
    :class="{ 'ivu-switch-checked': isChecked }":class="{ 'ivu-switch-checked': value }"
    @click.prevent="toggleSwitch"@click.prevent="$emit('input', !value)"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question