vue中如何通过函数传参数

 更新时间:2023年04月06日 08:37:37   作者:前端小问题  
这篇文章主要介绍了vue中如何通过函数传参数问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

vue通过函数传参数

一,通过点击事件本身的js特性传参。

<view class="center_menu">
                <view class="menu_item" v-for="item in menus" @click="toAddress(item.address)">
                    <image :src="item.icon" mode="aspectFill" ></image>
                    <text>{{item.name}}</text>
                </view>
            </view>

将所需要的参数直接@click=“toAddress(item.address)”,放在函数的括号内传递。接受的时候如下:

methods: {
            toAddress (e){
                console.log(e);
            }
        },

二,通过自定义属性传参,我经常用这种。

<view class="order_status">
                    <view class="status" v-for="item in status" @click="toAddress" data-id="1">
                        <image class="icon" :src="item.url" mode="aspectFill"></image>
                        <text>{{item.name}}</text>
                    </view>
                </view>

通过自定义属性data-id将字符串“1”传递过去。(这种方法小程序上经常使用)接受的时候如下:

methods: {
            toAddress (e){
                console.log(e.currentTarget.dataset.id);
            }
        },

三,将事件本身传递过去。

<view class="order_status">
                    <view class="status" v-for="item in status" @click="toAddress($event)" data-id="1">
                        <image class="icon" :src="item.url" mode="aspectFill"></image>
                        <text>{{item.name}}</text>
                    </view>
                </view>
methods: {
            toAddress (e){
                console.log(e);
            }
        },

vue事件函数传参

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <div>{{num}}</div>
        <div>
            <!-- 如果事件直接绑定函数名称,那么默认会传递事件对象作为事件函数的第一个参数 -->
            <button v-on:click='handle1'>点击1</button>
            <!-- 2、如果事件绑定函数调用,那么事件对象必须作为最后一个参数显示传递,
                 并且事件对象的名称必须是$event 
            -->
            <button v-on:click='handle2(123, 456, $event)'>点击2</button>
        </div>
    </div>
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript">
        var vm = new Vue({
            el: '#app',
            data: {
                num: 0
            },
            methods: {
                handle1: function(event) {
                    console.log(event.target.innerHTML)
                },
                handle2: function(p, p1, event) {
                    console.log(p, p1)
                    console.log(event.target.innerHTML)
                    this.num++;
                }
            }
        });
    </script>
</body>

</html>```

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

最新评论