vue.js - 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 位置,但现在使函数失败。使用它的正确方法是什么?
解决方案
你有办法在你的模板代码中访问“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
那么将是一个空数组。
推荐阅读
- google-bigquery - 我需要更正拼写错误,但 UPDATE 给出了 DML 错误
- cloudera-cdh - 将 hive 表导出到 mysql 时 sqoop1 挂断
- azure - Azure Monitor - 创建新订阅时如何创建警报?
- matlab - Matlab - 绘制特定像素(图像处理)
- c# - 登录后显示用户名不起作用
- jenkins - 詹金斯“何时”条件不适用于舞台环境
- sql - 选择 2 个表
- java - 用 retrofit2 模拟 curl -F
- android - 什么使变量的值在生命周期中变为空或回到初始化值
- graphql - GraphQL - 如何从检索到的模式中获取字段类型?