需求:Vue3 setup
父组件向子组件传值,子组件接收父组件传入的值;子组件向父组件传值,父组件接收的子组件传递的值。
父组件:parent.tsx
:
import { defineComponent, ref, reactive } from 'vue';
import TotalPreview from './components/TotalPreview'
export default defineComponent({
name: 'parent',
components: { TotalPreview },
setup() {
const count = ref(123);
const childNum = reactive({ num: 1 });
const onChildClick = (val: any) => {
childNum.num = val;
console.log('childNum',childNum); // 打印子组件向父组件传递的值
};
return () => (
<>
<div>
<h1>父组件接收的子组件传递的值:{childNum.num}</h1>
<TotalPreview num={count.value} onNumClick={onChildClick} />
</div>
</>
);
},
});
子组件:TotalPreview.tsx
:文章来源:https://www.toymoban.com/news/detail-649605.html
import { defineComponent, ref } from 'vue';
import { Button } from 'ant-design-vue';
export default defineComponent({
name: 'Child',
props: { num: Number },
emits: ["numClick"],
setup(props, { emit }) {
const parentNum = ref(props.num)
const count = ref(1);
const onclick = () => {
count.value++
// emit 子组件向父组件传值
emit('numClick', count.value);
}
return () => (
<div>
<h1>{'父组件传递给子组件的值:'+parentNum.value}</h1>
<h1>{'子组件显示count值:'+count.value}</h1>
<Button onClick={onclick}>点击按钮改变子组件的值,并向父组件传值</Button>
</div>
);
},
});
页面效果:
文章来源地址https://www.toymoban.com/news/detail-649605.html
到了这里,关于Vue3 setup tsx 子组件向父组件传值 emit的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!