javascript - VueJS $emit 无法将数据推送到父级
问题描述
所以我在$emit
开始工作向父母发送数据时遇到了问题。我希望做的是单击提交按钮从输入中获取数据,然后将结果发送给父级。我正在使用原型JSON
块来测试流程,因为我是 Vue 的新手。
这是一些填充文本,因为我需要克服太多代码与文本不足的问题。这是一些填充文本,因为我需要克服太多代码与文本不足的问题。
TypeError:无法在 eval 中读取未定义的属性“$emit”(SearchBar.vue?e266:42)
<template>
<div class="searchbox">
<datepicker v-model="fromdate" placeholder="Start Date" name="fromdate" class="datepicker"></datepicker>
<datepicker v-model="todate" placeholder="End Date" name="todate" class="datepicker"></datepicker>
<input type="text" v-model="namesearch" name="namesearch" placeholder="Username/Lastname"/>
<input type="text" v-model="titlesearch" name="titlesearch" placeholder="Title / Short Desc."/>
<input type="text" v-model="descsearch" name="descsearch" placeholder="Long Desc"/>
<button name="refreshresults" v-on:click="getresults">Do Search</button>
</div>
</template>
<script>
import Datepicker from 'vuejs-datepicker/dist/vuejs-datepicker.common.js'
import axios from 'axios'
export default {
name: 'SearchBar',
components:{
Datepicker
},
data(){
return {
fromdate:"",
todate:"",
namesearch:"",
titlesearch:"",
descsearch:""
}
},
methods:{
getresults: function(e){
const searchcriteria = {
fromdate: this.fromdate,
todate: this.todate,
namesearch: this.namesearch,
titlesearch: this.titlesearch,
descsearch: this.descsearch
}
axios.get('https://jsonplaceholder.typicode.com/todos')
.then(function (response) {
// handle success
console.log(response.data);
this.$emit('sendingInfo',searchcriteria);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
console.log('catchall');
});
}
}
}
</script>
<style>
.vdp-datepicker{
display:inline-block;
}
INPUT,BUTTON{
margin:5px;
display: inline-block;
padding:5px;
text-align: center;
font-weight: bold;
font-size: 15px;
}
</style>
解决方案
那是因为this
在您的 axios.then(function() {...})
回调中没有引用您的 VueJS 组件。如果您尝试登录this
到控制台,您将看到它不再指向您的 VueJS 组件。
由于您使用的是 ES6,因此只需使用箭头函数,以便它保留this
封闭范围内的词法:
axios.get('https://jsonplaceholder.typicode.com/todos')
.then(response => {
// handle success
console.log(response.data);
this.$emit('sendingInfo',searchcriteria);
})
推荐阅读
- c++ - 对类静态 constexpr 结构的未定义引用,g++ vs clang
- winapi - 有没有办法从 Win32 应用程序检测 Windows 10 中的焦点辅助(以前称为安静时间)的变化
- eclipse - eclipse ide中的空格(>>>>>>)和空格(......)有什么区别?
- sql - SQL Server 计数记录按月和位置按 4 周分组
- c# - 在 Windows server 2016、Window 10 上构建 .NET 4.0 项目
- powershell - Powershell 调用命令 $input
- laravel-5 - 使用 cboden/ratchet 我得到了 Interface 'Rachet\MessageComponentInterface' not found 错误
- java - 非独立 Spring 应用程序和 SSL
- regex - 如何在正则表达式中设置一个匹配高于另一个匹配的定义优先级
- android - NativeScript - 不支持可点击跨度