switch: add beforeChange hook (#1878)

This commit is contained in:
Summer
2021-04-25 22:53:09 -05:00
committed by GitHub
parent 045ea5df41
commit a1f521edec
7 changed files with 717 additions and 309 deletions

View File

@@ -1,5 +1,8 @@
import { mount } from '@vue/test-utils'
import Switch from '../src/index.vue'
import { nextTick } from 'vue'
jest.useFakeTimers()
describe('Switch.vue', () => {
@@ -228,4 +231,103 @@ describe('Switch.vue', () => {
await vm.$nextTick()
expect(inputEl.checked).toEqual(false)
})
test('beforeChange function return promise', async () => {
const wrapper = mount({
components: {
'el-switch': Switch,
},
template: `
<div>
<el-switch
v-model="value"
:loading="loading"
:before-change="beforeChange"
/>
</div>
`,
data() {
return {
value: true,
loading: false,
asyncResult: 'error',
}
},
methods: {
beforeChange() {
this.loading = true
return new Promise((resolve, reject) => {
setTimeout(() => {
this.loading = false
return this.asyncResult == 'success'
? resolve(true)
: reject(new Error('error'))
}, 1000)
})
},
},
})
const vm = wrapper.vm
const coreWrapper = wrapper.find('.el-switch__core')
coreWrapper.trigger('click')
jest.runAllTimers()
await nextTick()
expect(vm.value).toEqual(true)
vm.asyncResult = 'success'
coreWrapper.trigger('click')
jest.runAllTimers()
await nextTick()
expect(vm.value).toEqual(false)
coreWrapper.trigger('click')
jest.runAllTimers()
await nextTick()
expect(vm.value).toEqual(true)
})
test('beforeChange function return boolean', async () => {
const wrapper = mount({
components: {
'el-switch': Switch,
},
template: `
<div>
<el-switch
v-model="value"
:before-change="beforeChange"
/>
</div>
`,
data() {
return {
value: true,
result: false,
}
},
methods: {
beforeChange() {
// do something ...
return this.result
},
},
})
const vm = wrapper.vm
const coreWrapper = wrapper.find('.el-switch__core')
await coreWrapper.trigger('click')
expect(vm.value).toEqual(true)
vm.result = true
await coreWrapper.trigger('click')
expect(vm.value).toEqual(false)
await coreWrapper.trigger('click')
expect(vm.value).toEqual(true)
})
})

View File

@@ -43,8 +43,12 @@
<script lang='ts'>
import { defineComponent, computed, onMounted, ref, inject, nextTick, watch } from 'vue'
import { elFormKey, elFormItemKey } from '@element-plus/form'
import { isPromise } from '@vue/shared'
import { isBool } from '@element-plus/utils/util'
import throwError, { warn } from '@element-plus/utils/error'
import type { ElFormContext, ElFormItemContext } from '@element-plus/form'
import type { PropType } from 'vue'
type ValueType = boolean | string | number;
@@ -66,6 +70,7 @@ interface ISwitchProps {
validateEvent: boolean
id: string
loading:boolean
beforeChange?: () => (Promise<boolean> | boolean)
}
export default defineComponent({
@@ -132,6 +137,7 @@ export default defineComponent({
type: Boolean,
default: false,
},
beforeChange: Function as PropType<() => (Promise<boolean> | boolean)>,
},
emits: ['update:modelValue', 'change', 'input'],
setup(props: ISwitchProps, ctx) {
@@ -142,6 +148,8 @@ export default defineComponent({
const input = ref(null)
const core = ref(null)
const scope = 'ElSwitch'
watch(() => props.modelValue, () => {
isModelValue.value = true
})
@@ -191,7 +199,34 @@ export default defineComponent({
}
const switchValue = (): void => {
!switchDisabled.value && handleChange()
if (switchDisabled.value) return
const { beforeChange } = props
if (!beforeChange) {
handleChange()
return
}
const shouldChange = beforeChange()
const isExpectType = [isPromise(shouldChange), isBool(shouldChange)].some(i => i)
if (!isExpectType) {
throwError(scope, 'beforeChange must return type `Promise<boolean>` or `boolean`')
}
if (isPromise(shouldChange)) {
shouldChange.then(result => {
if (result) {
handleChange()
}
}).catch(e => {
if (process.env.NODE_ENV !== 'production') {
warn(scope, `some error occurred: ${e}`)
}
})
} else if (shouldChange) {
handleChange()
}
}
const setBackgroundColor = (): void => {
@@ -202,6 +237,10 @@ export default defineComponent({
coreEl.children[0].style.color = newColor
}
const focus = (): void => {
input.value?.focus?.()
}
onMounted(() => {
if (props.activeValue || props.inactiveValue) {
setBackgroundColor()
@@ -217,6 +256,7 @@ export default defineComponent({
checked,
handleChange,
switchValue,
focus,
}
},
})

View File

@@ -3,15 +3,12 @@
Switch is used for switching between two opposing states.
### Basic usage
:::demo Bind `v-model` to a `Boolean` typed variable. The `active-color` and `inactive-color` attribute decides the background color in two states.
```html
<el-switch v-model="value1">
</el-switch>
<el-switch
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949">
<el-switch v-model="value1"> </el-switch>
<el-switch v-model="value2" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
<script>
@@ -19,22 +16,25 @@ Switch is used for switching between two opposing states.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Text description
:::demo You can add `active-text` and `inactive-text` attribute to show texts.
```html
<el-switch
v-model="value1"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<el-switch
style="display: block"
@@ -42,7 +42,8 @@ Switch is used for switching between two opposing states.
active-color="#13ce66"
inactive-color="#ff4949"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<script>
@@ -50,12 +51,13 @@ Switch is used for switching between two opposing states.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Extended value types
@@ -69,7 +71,8 @@ Switch is used for switching between two opposing states.
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
inactive-value="0"
>
</el-switch>
</el-tooltip>
@@ -77,10 +80,10 @@ Switch is used for switching between two opposing states.
export default {
data() {
return {
value: '100'
value: '100',
}
}
};
},
}
</script>
```
@@ -91,26 +94,21 @@ Switch is used for switching between two opposing states.
:::demo Adding the `disabled` attribute disables Switch.
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<el-switch v-model="value1" disabled> </el-switch>
<el-switch v-model="value2" disabled> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### Loading
@@ -118,53 +116,110 @@ Switch is used for switching between two opposing states.
:::demo Setting the `loading` attribute to `true` indicates a loading state on the Switch.
```html
<el-switch
v-model="value1"
loading>
</el-switch>
<el-switch
v-model="value2"
loading>
</el-switch>
<el-switch v-model="value1" loading> </el-switch>
<el-switch v-model="value2" loading> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### prevent switching
:::demo set the `beforeChange` property, If `false` is returned or a `Promise` is returned and then is rejected, will stop switching.
```html
<el-switch v-model="value1" :loading="loading1" :beforeChange="beforeChange1">
</el-switch>
<el-switch v-model="value2" :loading="loading2" :beforeChange="beforeChange2">
</el-switch>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
export default {
setup() {
const status1 = reactive({
value1: false,
loading1: false,
})
const beforeChange1 = () => {
status1.loading1 = true
return new Promise(resolve => {
setTimeout(() => {
status1.loading1 = false
ElMessage.success('switch success')
return resolve(true)
}, 1000)
})
}
const status2 = reactive({
value2: false,
loading2: false,
})
const beforeChange2 = () => {
status2.loading2 = true
return new Promise((resolve, reject) => {
setTimeout(() => {
status2.loading2 = false
ElMessage.error('switch failed')
return reject(new Error('error'))
}, 1000)
})
}
return {
...toRefs(status1),
...toRefs(status2),
beforeChange1,
beforeChange2,
}
},
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|-----| ----| ----| ----|---- |
| value / v-model | binding value, it should be equivalent to either `active-value` or `inactive-value`, by default it's `boolean` type | boolean / string / number | — | — |
| disabled | whether Switch is disabled | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | width of Switch | number | — | 40 |
| active-icon-class | class name of the icon displayed when in `on` state, overrides `active-text` | string | — | — |
| inactive-icon-class |class name of the icon displayed when in `off` state, overrides `inactive-text`| string | — | — |
| active-text | text displayed when in `on` state | string | — | — |
| inactive-text | text displayed when in `off` state | string | — | — |
| active-value | switch value when in `on` state | boolean / string / number | — | true |
| inactive-value | switch value when in `off` state | boolean / string / number | — | false |
| active-color | background color when in `on` state | string | — | #409EFF |
| inactive-color | background color when in `off` state | string | — | #C0CCDA |
| name | input name of Switch | string | — | — |
| validate-event | whether to trigger form validation | boolean | - | true |
| Attribute | Description | Type | Accepted Values | Default |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | --------------- | ------- |
| value / v-model | binding value, it should be equivalent to either `active-value` or `inactive-value`, by default it's `boolean` type | boolean / string / number | — | — |
| disabled | whether Switch is disabled | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | width of Switch | number | — | 40 |
| active-icon-class | class name of the icon displayed when in `on` state, overrides `active-text` | string | — | — |
| inactive-icon-class | class name of the icon displayed when in `off` state, overrides `inactive-text` | string | — | — |
| active-text | text displayed when in `on` state | string | — | — |
| inactive-text | text displayed when in `off` state | string | — | — |
| active-value | switch value when in `on` state | boolean / string / number | — | true |
| inactive-value | switch value when in `off` state | boolean / string / number | — | false |
| active-color | background color when in `on` state | string | — | #409EFF |
| inactive-color | background color when in `off` state | string | — | #C0CCDA |
| name | input name of Switch | string | — | — |
| validate-event | whether to trigger form validation | boolean | — | true |
| before-change | before-change hook before the switch state changes. If `false` is returned or a `Promise` is returned and then is rejected, will stop switching | function | — | — |
### Events
| Event Name | Description | Parameters |
| ---- | ----| ---- |
| change | triggers when value changes | value after changing |
| Event Name | Description | Parameters |
| ---------- | --------------------------- | -------------------- |
| change | triggers when value changes | value after changing |
### Methods
| Method | Description | Parameters |
| ------|--------|------- |
| focus | focus the Switch component | — |
| Method | Description | Parameters |
| ------ | -------------------------- | ---------- |
| focus | focus the Switch component | — |

View File

@@ -7,12 +7,8 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
:::demo Enlace `v-model` a una variable de tipo `Boolean`. Los atributos `active-color` y `inactive-color` deciden el color de fondo en cada estado.
```html
<el-switch v-model="value1">
</el-switch>
<el-switch
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949">
<el-switch v-model="value1"> </el-switch>
<el-switch v-model="value2" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
<script>
@@ -20,22 +16,25 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Texto de descripción
:::demo Puede agregar los atributos `active-text` y `inactive-text` para mostrar los textos.
```html
<el-switch
v-model="value1"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<el-switch
style="display: block"
@@ -43,7 +42,8 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
active-color="#13ce66"
inactive-color="#ff4949"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<script>
@@ -51,12 +51,13 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Tipos de valores extendidos
@@ -70,7 +71,8 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
inactive-value="0"
>
</el-switch>
</el-tooltip>
@@ -78,10 +80,10 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
export default {
data() {
return {
value: '100'
value: '100',
}
}
};
},
}
</script>
```
@@ -92,26 +94,21 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
:::demo Agregar el atributo `disabled` desactiva el componente Switch.
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<el-switch v-model="value1" disabled> </el-switch>
<el-switch v-model="value2" disabled> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### Loading
@@ -119,54 +116,112 @@ Switch es utilizado para realizar cambios entre dos estados opuestos.
:::demo Setting the `loading` attribute to `true` indicates a loading state on the Switch.
```html
<el-switch
v-model="value1"
loading>
</el-switch>
<el-switch
v-model="value2"
loading>
</el-switch>
<el-switch v-model="value1" loading> </el-switch>
<el-switch v-model="value2" loading> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### prevent switching
:::demo set the `beforeChange` property, If `false` is returned or a `Promise` is returned and then is rejected, will stop switching.
```html
<el-switch v-model="value1" :loading="loading1" :beforeChange="beforeChange1">
</el-switch>
<el-switch v-model="value2" :loading="loading2" :beforeChange="beforeChange2">
</el-switch>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
export default {
setup() {
const status1 = reactive({
value1: false,
loading1: false,
})
const beforeChange1 = () => {
status1.loading1 = true
return new Promise(resolve => {
setTimeout(() => {
status1.loading1 = false
ElMessage.success('switch success')
return resolve(true)
}, 1000)
})
}
const status2 = reactive({
value2: false,
loading2: false,
})
const beforeChange2 = () => {
status2.loading2 = true
return new Promise((resolve, reject) => {
setTimeout(() => {
status2.loading2 = false
ElMessage.error('switch failed')
return reject(new Error('error'))
}, 1000)
})
}
return {
...toRefs(status1),
...toRefs(status2),
beforeChange1,
beforeChange2,
}
},
}
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------------- | ---------------------------------------- | ------------------------- | ----------------- | ----------- |
| value / v-model |valor vinculante, debe ser equivalente al `active-value` o al `inactive-value`. El tipo por defecto es el tipo `boolean`. | boolean / string / number | — | — |
| disabled | si Switch esta deshabilitado | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | ancho del componente Switch | number | — | 40 |
| active-icon-class | nombre de la clase del icono mostrado en el estado `on`, sobrescribe `active-text` | string | — | — |
| inactive-icon-class | nombre de la clase del icono mostrado en el estado `off`, sobrescribe `inactive-text` | string | — | — |
| active-text | texto mostrado en el estado `on` | string | — | — |
| inactive-text | texto mostrado en el estado `off` | string | — | — |
| active-value | cambia su valor cuando se encuentra en el estado `on` | boolean / string / number | — | true |
| inactive-value | cambia su valor cuando se encuentra en el estado `off` | boolean / string / number | — | false |
| active-color | color de fondo cuando se encuentra en el estado `on` | string | — | #409EFF |
| inactive-color | color de fondo cuando se encuentra en el estado `off` | string | — | #C0CCDA |
| name | nombre de entrada del componente Switch | string | — | — |
| validate-event | si se debe lanzar la validación de formulario | boolean | - | true |
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | ----------- |
| value / v-model | valor vinculante, debe ser equivalente al `active-value` o al `inactive-value`. El tipo por defecto es el tipo `boolean`. | boolean / string / number | — | — |
| disabled | si Switch esta deshabilitado | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | ancho del componente Switch | number | — | 40 |
| active-icon-class | nombre de la clase del icono mostrado en el estado `on`, sobrescribe `active-text` | string | — | — |
| inactive-icon-class | nombre de la clase del icono mostrado en el estado `off`, sobrescribe `inactive-text` | string | — | — |
| active-text | texto mostrado en el estado `on` | string | — | — |
| inactive-text | texto mostrado en el estado `off` | string | — | — |
| active-value | cambia su valor cuando se encuentra en el estado `on` | boolean / string / number | — | true |
| inactive-value | cambia su valor cuando se encuentra en el estado `off` | boolean / string / number | — | false |
| active-color | color de fondo cuando se encuentra en el estado `on` | string | — | #409EFF |
| inactive-color | color de fondo cuando se encuentra en el estado `off` | string | — | #C0CCDA |
| name | nombre de entrada del componente Switch | string | — | — |
| validate-event | si se debe lanzar la validación de formulario | boolean | | true |
| before-change | before-change hook before the switch state changes. If `false` is returned or a `Promise` is returned and then is rejected, will stop switching | function | — | — |
### Eventos
| Nombre del evento | Descripción | Parametro |
| ----------------- | --------------------------------- | --------- |
| change | se dispara cuando el valor cambia | valor |
después de cambiar
### Metodos
| Metodo | Descripción | Parametro |
| ------ | ------------------------- | --------- |
| focus | foco al componente Switch | — |

View File

@@ -7,12 +7,8 @@ Switch est utilisé pour choisir entre deux états opposés.
:::demo Liez `v-model` à une variable de type `Boolean`. Les attributs `active-color` et `inactive-color` déterminent les couleurs des deux états.
```html
<el-switch v-model="value1">
</el-switch>
<el-switch
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949">
<el-switch v-model="value1"> </el-switch>
<el-switch v-model="value2" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
<script>
@@ -20,12 +16,13 @@ Switch est utilisé pour choisir entre deux états opposés.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Description
@@ -36,7 +33,8 @@ Switch est utilisé pour choisir entre deux états opposés.
<el-switch
v-model="value1"
active-text="Paiement mensuel"
inactive-text="Paiement annuel">
inactive-text="Paiement annuel"
>
</el-switch>
<el-switch
style="display: block"
@@ -44,7 +42,8 @@ Switch est utilisé pour choisir entre deux états opposés.
active-color="#13ce66"
inactive-color="#ff4949"
active-text="Paiement mensuel"
inactive-text="Paiement annuel">
inactive-text="Paiement annuel"
>
</el-switch>
<script>
@@ -52,12 +51,13 @@ Switch est utilisé pour choisir entre deux états opposés.
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### Valeurs des états
@@ -71,7 +71,8 @@ Switch est utilisé pour choisir entre deux états opposés.
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
inactive-value="0"
>
</el-switch>
</el-tooltip>
@@ -79,10 +80,10 @@ Switch est utilisé pour choisir entre deux états opposés.
export default {
data() {
return {
value: '100'
value: '100',
}
}
};
},
}
</script>
```
@@ -93,26 +94,21 @@ Switch est utilisé pour choisir entre deux états opposés.
:::demo Ajoutez l'attribut `disabled` pour désactiver le switch.
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<el-switch v-model="value1" disabled> </el-switch>
<el-switch v-model="value2" disabled> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### Loading
@@ -120,54 +116,110 @@ Switch est utilisé pour choisir entre deux états opposés.
:::demo Setting the `loading` attribute to `true` indicates a loading state on the Switch.
```html
<el-switch
v-model="value1"
loading>
</el-switch>
<el-switch
v-model="value2"
loading>
</el-switch>
<el-switch v-model="value1" loading> </el-switch>
<el-switch v-model="value2" loading> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### Empêcher la commutation
:::demo Définissez la propriété `beforeChange`. Si elle renvoie false ou renvoie une promesse et est rejetée, le commutateur s'arrêtera.
```html
<el-switch v-model="value1" :loading="loading1" :beforeChange="beforeChange1">
</el-switch>
<el-switch v-model="value2" :loading="loading2" :beforeChange="beforeChange2">
</el-switch>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
export default {
setup() {
const status1 = reactive({
value1: false,
loading1: false,
})
const beforeChange1 = () => {
status1.loading1 = true
return new Promise(resolve => {
setTimeout(() => {
status1.loading1 = false
ElMessage.success('Basculer avec succès')
return resolve(true)
}, 1000)
})
}
const status2 = reactive({
value2: false,
loading2: false,
})
const beforeChange2 = () => {
status2.loading2 = true
return new Promise((resolve, reject) => {
setTimeout(() => {
status2.loading2 = false
ElMessage.error('Le commutateur a échoué')
return reject(new Error('error'))
}, 1000)
})
}
return {
...toRefs(status1),
...toRefs(status2),
beforeChange1,
beforeChange2,
}
},
}
</script>
```
:::
### Attributs
| Attribut | Description | Type | Valeurs acceptées | Défaut |
| ----| ----| ----| ----|---- |
| value / v-model | Valeur liée. Elle doit être équivalente à `active-value` ou `inactive-value`, par défaut elle est de type `boolean`. | boolean / string / number | — | — |
| disabled | Si le switch est désactivé. | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | Largeur du switch. | number | — | 40 |
| active-icon-class | Classe de l'icône de l'état `on`, écrase `active-text`. | string | — | — |
| inactive-icon-class | Classe de l'icône de l'état `off`, écrase `inactive-text`. | string | — | — |
| active-text | Texte affiché dans l'état `on`. | string | — | — |
| inactive-text | Texte affiché dans l'état `off`. | string | — | — |
| active-value | Valeur du switch dans l'état `on`. | boolean / string / number | — | true |
| inactive-value | Valeur du switch dans l'état `off`. | boolean / string / number | — | false |
| active-color | Couleur de fond de l'état `on`. | string | — | #409EFF |
| inactive-color | Couleur de fond de l'état `off`. | string | — | #C0CCDA |
| name| Nom du champ d'input du switch. | string | — | — |
| validate-event | Si la validation doit avoir lieu. | boolean | - | true |
| Attribut | Description | Type | Valeurs acceptées | Défaut |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | ----------------- | ------- |
| value / v-model | Valeur liée. Elle doit être équivalente à `active-value` ou `inactive-value`, par défaut elle est de type `boolean`. | boolean / string / number | — | — |
| disabled | Si le switch est désactivé. | boolean | — | false |
| loading | whether Switch is in loading state | boolean | — | false |
| width | Largeur du switch. | number | — | 40 |
| active-icon-class | Classe de l'icône de l'état `on`, écrase `active-text`. | string | — | — |
| inactive-icon-class | Classe de l'icône de l'état `off`, écrase `inactive-text`. | string | — | — |
| active-text | Texte affiché dans l'état `on`. | string | — | — |
| inactive-text | Texte affiché dans l'état `off`. | string | — | — |
| active-value | Valeur du switch dans l'état `on`. | boolean / string / number | — | true |
| inactive-value | Valeur du switch dans l'état `off`. | boolean / string / number | — | false |
| active-color | Couleur de fond de l'état `on`. | string | — | #409EFF |
| inactive-color | Couleur de fond de l'état `off`. | string | — | #C0CCDA |
| name | Nom du champ d'input du switch. | string | — | — |
| validate-event | Si la validation doit avoir lieu. | boolean | — | true |
| before-change | Le hook avant le changement d'état du commutateur. S'il renvoie false ou renvoie une promesse et est rejeté, le commutateur s'arrêtera. | function | — | — |
### Évènements
| Nom | Description | Paramètres |
| ---- | ----| ---- |
| Nom | Description | Paramètres |
| ------ | ------------------------------------ | --------------------------- |
| change | Se déclenche quand la valeur change. | La valeur après changement. |
### Méthodes
| Méthode | Description | Paramètres |
|-------|--------|------- |
| focus | Donne le focus au switch. | — |
| Méthode | Description | Paramètres |
| ------- | ------------------------- | ---------- |
| focus | Donne le focus au switch. | — |

View File

@@ -1,17 +1,14 @@
## スイッチ
スイッチは、2つの状態を切り替えるために使用されます。
スイッチは、2 つの状態を切り替えるために使用されます。
### 基本的な使い方
:::demo `v-model``Boolean` 型変数にバインドする。`active-color``inactive-color`属性は、2つの状態の背景色を決定する。
:::demo `v-model``Boolean` 型変数にバインドする。`active-color``inactive-color`属性は、2 つの状態の背景色を決定する。
```html
<el-switch v-model="value1">
</el-switch>
<el-switch
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949">
<el-switch v-model="value1"> </el-switch>
<el-switch v-model="value2" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
<script>
@@ -19,22 +16,25 @@
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### テキストの説明
:::demo テキストを表示するために `active-color``inactive-color` 属性を追加することができます。
```html
<el-switch
v-model="value1"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<el-switch
style="display: block"
@@ -42,7 +42,8 @@
active-color="#13ce66"
inactive-color="#ff4949"
active-text="Pay by month"
inactive-text="Pay by year">
inactive-text="Pay by year"
>
</el-switch>
<script>
@@ -50,12 +51,13 @@
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### 拡張された値型
@@ -69,7 +71,8 @@
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
inactive-value="0"
>
</el-switch>
</el-tooltip>
@@ -77,10 +80,10 @@
export default {
data() {
return {
value: '100'
value: '100',
}
}
};
},
}
</script>
```
@@ -91,26 +94,21 @@
:::demo `disabled`属性を追加すると、スイッチを無効にすることができます。
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<el-switch v-model="value1" disabled> </el-switch>
<el-switch v-model="value2" disabled> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### ローディング
@@ -118,53 +116,110 @@
:::demo `loading`属性を`true`に設定すると、ロード状態を表示することができます。
```html
<el-switch
v-model="value1"
loading>
</el-switch>
<el-switch
v-model="value2"
loading>
</el-switch>
<el-switch v-model="value1" loading> </el-switch>
<el-switch v-model="value2" loading> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### 切り替えを防ぐ
:::demo `beforeChange`プロパティを設定します。false を返すか、Promise を返し、拒否された場合は、切り替えを停止します。
```html
<el-switch v-model="value1" :loading="loading1" :beforeChange="beforeChange1">
</el-switch>
<el-switch v-model="value2" :loading="loading2" :beforeChange="beforeChange2">
</el-switch>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
export default {
setup() {
const status1 = reactive({
value1: false,
loading1: false,
})
const beforeChange1 = () => {
status1.loading1 = true
return new Promise(resolve => {
setTimeout(() => {
status1.loading1 = false
ElMessage.success('正常に切り替えます')
return resolve(true)
}, 1000)
})
}
const status2 = reactive({
value2: false,
loading2: false,
})
const beforeChange2 = () => {
status2.loading2 = true
return new Promise((resolve, reject) => {
setTimeout(() => {
status2.loading2 = false
ElMessage.error('スイッチに失敗しました')
return reject(new Error('error'))
}, 1000)
})
}
return {
...toRefs(status1),
...toRefs(status2),
beforeChange1,
beforeChange2,
}
},
}
</script>
```
:::
### 属性
| Attribute | Description | Type | Accepted Values | Default |
|-----| ----| ----| ----|---- |
| value / v-model | バインド値は、"active-value "または "inactive-value "と等しくなければなりません。デフォルトの型は "boolean "です。 | boolean / string / number | — | — |
| disabled | スイッチが無効になっているかどうか | boolean | — | false |
| loading | スイッチがロード中になっているかどうか | boolean | — | false |
| width | スイッチの幅 | number | — | 40 |
| active-icon-class | `on` 状態のときに表示されるアイコンのクラス名で、`active-text` を上書きします。 | string | — | — |
| inactive-icon-class |`off` 状態のときに表示されるアイコンのクラス名で、`inactive-text` を上書きします。| string | — | — |
| active-text | `on` 状態のときに表示されるテキスト | string | — | — |
| inactive-text | `off` 状態のときに表示されるテキスト | string | — | — |
| active-value | `on` 状態のときのスイッチの値 | boolean / string / number | — | true |
| inactive-value | `off` 状態のときのスイッチの値 | boolean / string / number | — | false |
| active-color | `on` 状態のときの背景色 | string | — | #409EFF |
| inactive-color | `off` 状態のときの背景色 | string | — | #C0CCDA |
| name | スイッチのインプット名 | string | — | — |
| validate-event | フォームバリデーションをトリガするかどうか | boolean | - | true |
| Attribute | Description | Type | Accepted Values | Default |
| ------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------- | --------------- | ------- |
| value / v-model | バインド値は、"active-value "または "inactive-value "と等しくなければなりません。デフォルトの型は "boolean "です。 | boolean / string / number | — | — |
| disabled | スイッチが無効になっているかどうか | boolean | — | false |
| loading | スイッチがロード中になっているかどうか | boolean | — | false |
| width | スイッチの幅 | number | — | 40 |
| active-icon-class | `on` 状態のときに表示されるアイコンのクラス名で、`active-text` を上書きします。 | string | — | — |
| inactive-icon-class | `off` 状態のときに表示されるアイコンのクラス名で、`inactive-text` を上書きします。 | string | — | — |
| active-text | `on` 状態のときに表示されるテキスト | string | — | — |
| inactive-text | `off` 状態のときに表示されるテキスト | string | — | — |
| active-value | `on` 状態のときのスイッチの値 | boolean / string / number | — | true |
| inactive-value | `off` 状態のときのスイッチの値 | boolean / string / number | — | false |
| active-color | `on` 状態のときの背景色 | string | — | #409EFF |
| inactive-color | `off` 状態のときの背景色 | string | — | #C0CCDA |
| name | スイッチのインプット名 | string | — | — |
| validate-event | フォームバリデーションをトリガするかどうか | boolean | — | true |
| before-change | スイッチの状態が変化する前のフックは、false を返すか、Promise を返し、切り替えを停止するために拒否されます | function | — | — |
### イベント
| Event Name | Description | Parameters |
| ---- | ----| ---- |
| change | 値が変わるとトリガー | value after changing |
| Event Name | Description | Parameters |
| ---------- | -------------------- | -------------------- |
| change | 値が変わるとトリガー | value after changing |
### メソッド
| Method | Description | Parameters |
| ------|--------|------- |
| focus | スイッチコンポーネントにフォーカス | — |
| Method | Description | Parameters |
| ------ | ---------------------------------- | ---------- |
| focus | スイッチコンポーネントにフォーカス | — |

View File

@@ -7,22 +7,20 @@
:::demo 绑定`v-model`到一个`Boolean`类型的变量。可以使用`active-color`属性与`inactive-color`属性来设置开关的背景色。
```html
<el-switch
v-model="value"
active-color="#13ce66"
inactive-color="#ff4949">
<el-switch v-model="value" active-color="#13ce66" inactive-color="#ff4949">
</el-switch>
<script>
export default {
data() {
return {
value: true
value: true,
}
}
};
},
}
</script>
```
:::
### 文字描述
@@ -30,10 +28,7 @@
:::demo 使用`active-text`属性与`inactive-text`属性来设置开关的文字描述。
```html
<el-switch
v-model="value1"
active-text="按月付费"
inactive-text="按年付费">
<el-switch v-model="value1" active-text="按月付费" inactive-text="按年付费">
</el-switch>
<el-switch
style="display: block"
@@ -41,7 +36,8 @@
active-color="#13ce66"
inactive-color="#ff4949"
active-text="按月付费"
inactive-text="按年付费">
inactive-text="按年付费"
>
</el-switch>
<script>
@@ -49,12 +45,13 @@
data() {
return {
value1: true,
value2: true
value2: true,
}
}
};
},
}
</script>
```
:::
### 扩展的 value 类型
@@ -68,7 +65,8 @@
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
inactive-value="0"
>
</el-switch>
</el-tooltip>
@@ -76,10 +74,10 @@
export default {
data() {
return {
value: '100'
value: '100',
}
}
};
},
}
</script>
```
@@ -89,81 +87,132 @@
:::demo 设置`disabled`属性,接受一个`Boolean`,设置`true`即可禁用。
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<el-switch v-model="value1" disabled> </el-switch>
<el-switch v-model="value2" disabled> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### 加载中
:::demo 设置`loading`属性,接受一个`Boolean`,设置`true`即加载中状态。
```html
<el-switch
v-model="value1"
loading>
</el-switch>
<el-switch
v-model="value2"
loading>
</el-switch>
<el-switch v-model="value1" loading> </el-switch>
<el-switch v-model="value2" loading> </el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
value2: false,
}
}
};
},
}
</script>
```
:::
### 阻止切换
:::demo 设置`beforeChange`属性,若返回 false 或者返回 Promise 且被 reject则停止切换。
```html
<el-switch v-model="value1" :loading="loading1" :beforeChange="beforeChange1">
</el-switch>
<el-switch v-model="value2" :loading="loading2" :beforeChange="beforeChange2">
</el-switch>
<script>
import { reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
export default {
setup() {
const status1 = reactive({
value1: false,
loading1: false,
})
const beforeChange1 = () => {
status1.loading1 = true
return new Promise(resolve => {
setTimeout(() => {
status1.loading1 = false
ElMessage.success('切换成功')
return resolve(true)
}, 1000)
})
}
const status2 = reactive({
value2: false,
loading2: false,
})
const beforeChange2 = () => {
status2.loading2 = true
return new Promise((resolve, reject) => {
setTimeout(() => {
status2.loading2 = false
ElMessage.error('切换失败')
return reject(new Error('error'))
}, 1000)
})
}
return {
...toRefs(status1),
...toRefs(status2),
beforeChange1,
beforeChange2,
}
},
}
</script>
```
:::
### Attributes
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | 绑定值,必须等于`active-value``inactive-value`,默认为`Boolean`类型 | boolean / string / number | — | — |
| disabled | 是否禁用 | boolean | — | false |
| loading | 是否显示加载中 | boolean | — | false |
| width | switch 的宽度(像素) | number | — | 40 |
| active-icon-class | switch 打开时所显示图标的类名,设置此项会忽略 `active-text` | string | — | — |
| inactive-icon-class | switch 关闭时所显示图标的类名,设置此项会忽略 `inactive-text` | string | — | — |
| active-text | switch 打开时的文字描述 | string | — | — |
| inactive-text | switch 关闭时的文字描述 | string | — | — |
| active-value | switch 打开时的值 | boolean / string / number | — | true |
| inactive-value | switch 关闭时的值 | boolean / string / number | — | false |
| active-color | switch 打开时的背景色 | string | — | #409EFF |
| inactive-color | switch 关闭时的背景色 | string | — | #C0CCDA |
| name | switch 对应的 name 属性 | string | — | — |
| validate-event | 改变 switch 状态时是否触发表单的校验 | boolean | - | true |
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| ------------------- | --------------------------------------------------------------------------- | ------------------------- | ------ | ------- |
| value / v-model | 绑定值,必须等于`active-value``inactive-value`,默认为`Boolean`类型 | boolean / string / number | — | — |
| disabled | 是否禁用 | boolean | — | false |
| loading | 是否显示加载中 | boolean | — | false |
| width | switch 的宽度(像素) | number | — | 40 |
| active-icon-class | switch 打开时所显示图标的类名,设置此项会忽略 `active-text` | string | — | — |
| inactive-icon-class | switch 关闭时所显示图标的类名,设置此项会忽略 `inactive-text` | string | — | — |
| active-text | switch 打开时的文字描述 | string | — | — |
| inactive-text | switch 关闭时的文字描述 | string | — | — |
| active-value | switch 打开时的值 | boolean / string / number | — | true |
| inactive-value | switch 关闭时的值 | boolean / string / number | — | false |
| active-color | switch 打开时的背景色 | string | — | #409EFF |
| inactive-color | switch 关闭时的背景色 | string | — | #C0CCDA |
| name | switch 对应的 name 属性 | string | — | — |
| validate-event | 改变 switch 状态时是否触发表单的校验 | boolean | — | true |
| before-change | switch 状态改变前的钩子,返回 false 或者返回 Promise 且被 reject 则停止切换 | function | — | — |
### Events
| 事件名称 | 说明 | 回调参数 |
|---------- |-------- |---------- |
| change | switch 状态发生变化时的回调函数 | 新状态的值 |
| 事件名称 | 说明 | 回调参数 |
| -------- | ------------------------------- | ---------- |
| change | switch 状态发生变化时的回调函数 | 新状态的值 |
### Methods
| 方法名 | 说明 | 参数 |
| ---- | ---- | ---- |
| focus | 使 Switch 获取焦点 | - |
| 方法名 | 说明 | 参数 |
| ------ | ------------------ | ---- |
| focus | 使 Switch 获取焦点 | - |