此文章基于setup script语法糖,个人使用整理,不定期更新
1.双方绑定
// 组件
<template>
<el-select v-model="selectValue" placeholder="选择" size="small" @change="onChange">
<el-option label="1" value="1"></el-option>
<el-option label="2" value="2"></el-option>
<el-option label="3" value="3"></el-option>
</el-select>
</template>
<script setup>
import {ref, watch, defineProps, defineEmits} from 'vue';
const props = defineProps({
modelValue: {
type: String,
default: ''
}
})
const emit = defineEmits(['update:modelValue']);
const selectValue = ref(props.modelValue);
watch(() => props.modelValue, () => {
selectValue.value = props.modelValue
});
function onChange(value) {
emit('update:modelValue', value)
};
</script>
// 调用
<me-select v-model="meValue"></me-select>
2.父组件调子组件方法
// 子组件
function meFn() {
}
defineExpose({
meFn
})
// 父组件
<me-select ref="selectRefs"></me-select>
<script setup>
import {ref} from 'vue';
const selectRefs = ref(null)
function onSelect(){
selectRefs.value.meFn()
}
</script>
3.子组件调父组件方法
// 子组件
<script setup>
import {ref, defineEmits} from 'vue';
// 需要注册事件
const emit = defineEmits(['select'])
function subSelect() {
emit('select', 'value')
}
</script>
// 父组件
<me-select @select='onSelect'></me-select>
<script setup>
function onSelect(value){
}
</script>