- child.tsx
import { defineComponent } from 'vue';
// 响应式数据需要放在函数外面,或者放在setup里面
const data1 = ref(123);
function myComponent() {
const data2 = ref(34); // 在这里定义ref 无法响应式
function data2ClickHanlder() {
data2.value++;
console.log(data2.value); // 35
// other logic here...
}
function data1ClickHanlder() {
data1.value++;
console.log(data1.value); // 124
// other logic here...
}
return (
<>
<div>sklfjsvnsldfjsd</div>
<div>{data1.value}</div>
<div>{data2.value}</div>
<button onClick={() => data2ClickHanlder()}>sdf</button>
<button onClick={() => data1ClickHanlder()}>dsksf</button>
</>
);
}
export default defineComponent({
props: {
modelValue: {
type: [Number, String],
default: 0,
required: true
}
},
emits: {
'update:model-value': (val) => true
},
// setup 第一个参数是props,第二个参数是类似this的参数,可以获取到各种,包括emit,slots等
setup(props, self) {
const { emit, slots } = self;
console.log(props, 'props');
console.log(self, 'self');
function clickHandler() {
data1.value++;
console.log(data1.value); // 124
// other logic here...
}
function emitInput(e) {
console.log(e?.target.value); // 34
self.emit('update:model-value', e?.target.value);
}
const arr = [234, 34234];
return (props) => {
console.log(props, 'clickHandler');
return (
<>
{myComponent()}
<div>{data1.value}</div>
<button onClick={() => clickHandler()}>btn</button>
<div>
<input type="text" value={props.modelValue} onInput={(e) => emit('update:model-value', e?.target.value)} />
</div>
<div>{slots.default?.()}</div>
<div>{arr?.[0]}</div>
</>
);
};
}
});
- 父组件
<template>
<div class='box'>
demo
<child v-model="myInputValue">
<template #default>
slot 测试
</template>
</child>
{{ myInputValue }}
</div>
</template>
<script lang='ts' setup>
// import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import child from './components/child';
const myInputValue = ref()
watch(myInputValue, (val) => {
console.log(val, "myInputValue")
})
</script>
<style lang='scss' scoped></style>
总结
- setup 第一个参数是props,第二个参数是类似this的参数,可以获取到各种,包括emit,slots等
- 响应式数据需要放在函数外面,或者放在setup里面
- modelValue 实现v-model数据接收,update:model-value实现数据外传