VUE3
子组件
<template>
<view class="">
<view class="" @click="handleClick">1</view>
<view class="" @click="handleClick2">2</view>
</view>
</template>
<script setup>
const emit = defineEmits(['handleOneArg', 'handleArgs']);
const handleClick = () => {
emit('handleOneArg', '1');
};
const handleClick2 = () => {
emit('handleArgs', '1', '2');
};
</script>
传递单值与vue2一致。
传递多值可以参考如下写法:
父组件
<template>
<view class="content">
<test-component @handleOneArg="getOneArg($event, 'newArg')" @handleArgs="(...args) => getArgs(...args, 'newArgs')"></test-component>
</view>
</template>
<script setup>
import TestComponent from './components/test-component.vue';
const getOneArg = (arg, addArg) => {
console.log(arg, addArg);
};
const getArgs = (arg1, arg2, addArg) => {
console.log(arg1, arg2, addArg);
};
</script>
此处因为我要直接获取所有字符串,所以使用@handleArgs="(...args) => getArgs(...args, 'newArgs')"
的写法。
如果要跟vue2一样获取一个args数组,可以使用@handleArgs="(...args) => getArgs(args, 'newArgs')"
的写法,不解构。
VUE2
子组件
<template>
<view class="">
<view class="" @click="handleClick">1</view>
<view class="" @click="handleClick2">2</view>
</view>
</template>
<script>
export default {
methods: {
handleClick() {
// 传递单值
this.$emit('handleOneArg', '1');
},
handleClick2() {
// 传递多值
this.$emit('handleArgs', '1', '2');
}
}
};
</script>
传递单值时,父组件可以使用$event代替子组件传入的值。
传递多值时,父组件可以通过arguments字段,该字段为子组件传入的值组成的数组。
具体示例如下:
父组件
<template>
<view class="content">
<test-component @handleOneArg="getOneArg($event, 'newArg')" @handleArgs="getArgs(arguments, 'newArgs')"></test-component>
</view>
</template>
<script>
import TestComponent from './components/test-component.vue';
export default {
components: {
TestComponent
},
methods: {
getOneArg(arg, addArg) {
console.log(arg, addArg); // 1 newArg
},
getArgs(arg1, addArg) {
console.log(arg1, addArg); // ['1','2'] 'newArgs'
}
}
};
</script>
转自:https://blog.csdn.net/weixin_43668101/article/details/137465010
标签:vue,const,args,addArg,handleArgs,参数,组件,getArgs From: https://www.cnblogs.com/axingya/p/18634772