Vue 2:无法在组件的点击事件上找到方法
2017-02-09
3200
在我的 vue 应用中,我在点击事件上调用一个函数,该函数位于组件中。以下是组件代码:
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
@click.stop="addBoard"
class="btn btn-success btn-xs btn-block"
>
Add Board
</button>
</div>
</div>
</div>
`
} )
以下是 vue 应用实例:
var boardItem = new Vue( {
el: "#board-item",
data: {
boards: [
{ name: 'learning vue 2' }
],
newBoard: [],
viewNewBoard: true
},
methods: {
displayNewBoard: function() {
event.preventDefault()
if( this.viewNewBoard == false ) {
this.viewNewBoard = true
} else {
this.viewNewBoard = false
}
},
addBoard: function() {
console.log( 'add board' )
}
}
} )
现在,当我单击上述组件中的
Add Board
按钮时,它会显示此错误:
Uncaught ReferenceError: addBoard is not defined at click (eval at Xr (vue.min.js:7), :2:455) at HTMLButtonElement.invoker (vue.min.js:6)
似乎组件中的按钮找不到
addBoard
方法,该方法写在同一个文件中!
我这里遗漏了什么?
2个回答
尝试:
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
@click.stop="addBoard"
class="btn btn-success btn-xs btn-block"
>
Add Board
</button>
</div>
</div>
</div>
`,
methods: {
addBoard: function(){ console.log('add board');}
}
} )
Bert
2017-02-09
这里有一些变化,如果您想与不相关的组件共享事件,您必须使用新的 vue 实例来触发这些事件并进行监听。因此,根据您的代码,这应该会有所帮助。
window.Event = new Vue();
Vue.component( 'new-board', {
template: `
<div>
<br/>
<div class="panel panel-primary">
<div class="panel-heading">
Create New Board
</div>
<div class="panel-body">
<input class="form-control" placeholder="Board Name"/>
<button
style="margin-top: 5px;"
@click.stop="addBoard" // keep this as the name of the local method
class="btn btn-success btn-xs btn-block">
Add Board
</button>
</div>
</div>
</div>
`,
methods:{
addBoard(){
// fire the event, also you can add any params
Event.$emit('callAddBoard',data)
}
}
} )
并且主实例应该监听该事件
var boardItem = new Vue( {
el: "#board-item",
data: {
boards: [
{ name: 'learning vue 2' }
],
newBoard: [],
viewNewBoard: true
},
methods: {
displayNewBoard: function() {
event.preventDefault()
if( this.viewNewBoard == false ) {
this.viewNewBoard = true
} else {
this.viewNewBoard = false
}
},
addBoard: function() {
console.log( 'add board' )
}
},
created(){
// here you listen and excute the remote event from component, and apply a local method.
Event.$on('callAddBoard', this.addBoard)
}
} )
据我尝试,这是可行的,您可以将事件发送到任何组件,而无需通过主实例。
deadPoet
2017-09-19