首页 > 解决方案 > VueJS将初始值传递给方法中的函数

问题描述

我有这个 VueJS 代码,它有一个postdata链接到按钮点击的方法<button class="btn btn-primary" v-on:click="postdata">Refresh</button>

window.onload = function () {
    var app = new Vue({
      delimiters: ['[[', ']]'],
      el: '#app',
      data: {
        jokes: [],

        joke_id: 1,
        dadjokes_id: 1,
        tweet_id: 1,
      },
      methods: {
        postdata: function (retrieve_data = []){
            initial_data = {'id': 1, 'model-name': 'Joke'}

            if (retrieve_data) {
                initial_data = retrieve_data
                console.log(initial_data)
            }

            fetch("\start-jokes\/", {
                body: JSON.stringify(initial_data),
                cache: 'no-cache', 
                credentials: 'same-origin', 
                headers: {
                    'user-agent': 'Mozilla/4.0 MDN Example',
                    'content-type': 'application/json'
                },
                method: 'POST',
                mode: 'cors', 
                redirect: 'follow',
                referrer: 'no-referrer',
                })
                .then(response => response.json()).then((json) => {
                    this.jokes.push(...json['jokes'])
                })
        }
    }
    });
};

由于我想将一些数据传递给该函数,因此我一直在寻找解决它所具有的错误的方法。initial_data如果更改,我已经尝试记录。它记录鼠标点击

MouseEvent {isTrusted: true, screenX: 1166, screenY: 216, clientX: 1156, clientY: 129…}

与 x, y 位置,但现在使函数失败。使用它的正确方法是什么?

标签: vue.js

解决方案


你有办法在你的模板代码中访问“retreive_data”对象吗?因为你可以很容易地传递参数,只要你可以访问它们。以下是传递简单对象的方法:

  <button v-on:click="postdata({ str: 'Hey'})">
    Click me
  </button>

在你的 JS 中:

new Vue({
 el: "#app",
  ...
  methods: {
    postdata: function(obj) { // the Object wie pass in v-on:click
        alert(obj.str); // Alerts "Hey"
    }
  }
})

如果您无法访问模板中的数据,请使用数据中的字段来存储您想要的数据。

更新:如果您不想获取鼠标事件,但没有任何数据要传递,请执行一个空函数调用:

 <button v-on:click="postdata()">
    Click me
 </button>

retreive_data那么将是一个空数组。


推荐阅读