Skip to content

事件处理

事件处理

SunlightRadio 支持变化事件处理。

基础事件处理

您可以监听单选框的各种事件,实现自定义的业务逻辑。

基础事件演示

选中值:option1

变化事件

  • change 事件:当单选框选中状态发生变化时触发
change 事件:当选中状态变化时触发

选中值:option1

文档说明

事件处理概述

SunlightRadio 支持选择变化事件,方便开发者实现复杂的业务逻辑。

支持的事件列表

事件名说明触发时机参数
update:modelValue绑定值更新事件,用于双向数据绑定选中状态变化时val: string/number - 更新后的值
change变化事件选中状态发生变化时触发val: string/number - 选中后的值

事件使用方式

SunlightRadio 组件支持两种事件绑定方式:直接通过 v-on 绑定和通过 eventFunction 配置项绑定。

1. 直接通过 v-on 绑定事件

vue
<template>
  <SunlightRadio
    v-model="radioValue"
    :item="{
      options: options,
      placeholder: '请选择选项'
    }"
    @change="handleChange"
  />
</template>

<script setup>
import { ref } from 'vue';
import { SunlightRadio } from 'sunlight-ui';
import { ElMessage } from 'element-plus';

const radioValue = ref('option1');
const options = [
  { label: '选项一', value: 'option1' },
  { label: '选项二', value: 'option2' },
  { label: '选项三', value: 'option3' },
  { label: '选项四', value: 'option4' }
];

function handleChange(val) {
  ElMessage({
    message: `选择变化: ${val}`,
    type: 'success',
  });
}
</script>

2. 通过 eventFunction 配置项绑定事件

vue
<template>
  <SunlightRadio
    v-model="radioValue"
    :item="{
      options: options,
      placeholder: '请选择选项',
      eventFunction: {
        change: (val) => {
          ElMessage({
            message: `eventFunction - 选择变化: ${val}`,
            type: 'success',
          });
        }
      }
    }"
  />
</template>

<script setup>
import { ref } from 'vue';
import { SunlightRadio } from 'sunlight-ui';
import { ElMessage } from 'element-plus';

const radioValue = ref('option1');
const options = [
  { label: '选项一', value: 'option1' },
  { label: '选项二', value: 'option2' },
  { label: '选项三', value: 'option3' },
  { label: '选项四', value: 'option4' }
];
</script>

3. 两种方式结合使用

直接绑定的事件和通过 eventFunction 配置的事件可以同时使用,都会被触发。

vue
<template>
  <SunlightRadio
    v-model="radioValue"
    :item="{
      options: options,
      placeholder: '请选择选项',
      eventFunction: {
        change: (val) => {
          ElMessage({
            message: `eventFunction - 选择变化: ${val}`,
            type: 'success',
          });
        }
      }
    }"
    @change="(val) => {
      ElMessage({
        message: `直接绑定 - 选择变化: ${val}`,
        type: 'success',
      });
    }"
  />
</template>

<script setup>
import { ref } from 'vue';
import { SunlightRadio } from 'sunlight-ui';
import { ElMessage } from 'element-plus';

const radioValue = ref('option1');
const options = [
  { label: '选项一', value: 'option1' },
  { label: '选项二', value: 'option2' },
  { label: '选项三', value: 'option3' },
  { label: '选项四', value: 'option4' }
];
</script>