【问题标题】:How to passing props id into methods in vue js如何将道具ID传递给vue js中的方法
【发布时间】:2017-04-28 04:32:42
【问题描述】:

我的项目使用 laravel 作为后端,使用 vue 作为前端。 我想将道具 id 传递给方法。 然后,当我单击按钮时,它将获取用户 ID 并运行继续进程。

在我看来,我使用它来将 id 传递给 vue 组件。

<conversation_send_message_form user_id="{{ $user->id }}"></conversation_send_message_form>

之后这是我的 vue 代码

export default {
    data() {
        return {
            body: null,
            recipients: [],
        }
    },
    props: ['id'],
    methods: {
        ...mapActions([
            'sendMessage'
        ]),
        send(){
            this.sendMessage({
                recipientIds: this.id,
                body: this.body
            }).then(() =>{
                this.recipients= []
                this.body = null
            })
        }
    }
}

这里会接收数据并进行处理

sendMessage ({dispatch, commit}, {body, recipientIds}) {
    return api.storeMessage({
        body: body,
        recipientIds: recipientIds
    }).then((response) => {
        console.log(response)
    })
},

我的 API

storeMessage({body, recipientIds}){
    return new Promise((resolve, reject) => {
        axios.post('/webapi/conversations', {
            body: body,
            recipients: recipientIds
        }).then((response) =>{
            resolve(response)
        })
    })
},

在我的场景中,我需要一个新方法来获取道具 id 并传递给新方法“Send”,在其中将 id 传递给接收者Ids,然后 api 将处理它。但我不知道如何获得道具 ID。谁能帮帮我?

【问题讨论】:

  • 您可以使用“this”访问方法内的数据。例如,this.id 将是存储在 id 属性中的数据。

标签: javascript php laravel vue.js


【解决方案1】:

您有两种方法可以将数据传递给您的 vue 组件,一种是使用静态道具

<conversation_send_message_form user_id="15"></conversation_send_message_form>

另一个是使用动态属性

<conversation_send_message_form v-bind:user_id="user.id"></conversation_send_message_form>

注意 laravel Blade 与类似 mustache 的语法

这些属性是通过“props”在组件中接收的,并且可以在 js 中使用 this.PROPNAME 访问(并且可以直接在模板中使用 PROPNAME 访问)所以你唯一的问题是名称不匹配,只需更改

export default {
    props: ['userId'],
    send() {
            this.sendMessage({
                recipientIds: this.userId,
                body: this.body
            }).then(() =>{
                this.recipients= []
                this.body = null
            })
     },
}

还要注意使用 camelCase 与 kebab-case 命名:https://vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 2023-03-24
    • 1970-01-01
    • 2020-01-30
    • 2019-02-03
    • 2018-05-29
    • 2020-03-30
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多