javascript - Vue.js 方法未定义
问题描述
这是方法的一些问题,我的组件无法访问方法。我是否需要将诸如 prop 之类的方法传递给组件?
这是我的html:
<guests v-bind="guests"></guests>
这是我的 js 文件中的组件
var guestsComponent = Vue.component("guests", {
props: ['adultCount', 'childCount'],
template: `
<div class="guests-total">
<div>
<a @click="decrementAdult"></a>
<a @click="incrementAdult"></a>
<input type="text" placeholder="adults"/> {{adultCount}}
</div>
</div>
`
});
在同一个 js 文件中,我的 vue init 和方法
var app = new Vue({
el: "#search",
components: {
"guests": guestsComponent
},
data() {
return {
guests: {
adultCount: 0,
childCount: 0
}
};
},
methods: {
decrementAdult() {
this.guests.adultCount++
},
incrementAdult() {
this.guests.adultCount--
}
}
});
当我使用道具时,我可以毫无问题地访问数据,但我不知道如何传递道具之类的方法,或者这是需要的?
这是控制台上的错误:
ReferenceError: decrementAdult is not defined
at o.eval (eval at xa (vue.min.js:NaN), <anonymous>:3:88)
at o.fn._render (vue.min.js?f6b5:6)
at o.eval (vue.min.js?f6b5:6)
at St.get (vue.min.js?f6b5:6)
at new St (vue.min.js?f6b5:6)
at o.hn.$mount (vue.min.js?f6b5:6)
at o.hn.$mount (vue.min.js?f6b5:6)
at init (vue.min.js?f6b5:6)
at eval (vue.min.js?f6b5:6)
at b (vue.min.js?f6b5:6)
解决方案
Since the click
events are done in the child component guests
you should emit an event to the parent component and handle it there like :
....
<a @click="$emit('decrement-adult')"></a>
...
in the parent component do :
<guests v-bind="guests" @decrement-adult="decrementAdult"></guests>
推荐阅读
- flutter - 在颤振中如何从函数中获取值?
- reactjs - 在已经更新后再次更新状态
- java - 为什么不会弹出我的 JOptionPane 错误消息?
- python - python telnet没有按“\ n”输入
- java - 使用 JPA 获取数据并使用 java 写入 txt 文件
- ansible - 基于 ansible stdout 值的回显消息
- python - 我可以根据同一位置的值在 folium 中添加标记吗?
- c# - SignalR 错误错误:由于服务器上的错误,无法调用“方法名”
- model-view-controller - 在 MVC .NET Core 中使用后退按钮时没有刷新页面
- javascript - 按端点请求格式化数据集