在我的vue应用程序中,我在click事件上调用一个函数,它位于一个组件中。这是组件代码:
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 app实例:
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
按钮时,它显示此错误:
未捕获的ReferenceError:未定义addBoard 点击(在Xr的eval(vue.min.js:7),:2:455) 在HTMLButtonElement.invoker(vue.min.js:6)
似乎组件中的按钮找不到addBoard
方法,该方法写在同一个文件中!
我在这里缺少什么?
答案 0 :(得分:1)
尝试:
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');}
}
} )
答案 1 :(得分:0)
此处进行一些更改,如果要与不相关的组件共享事件,则必须使用新的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)
}
} )
据我尝试过这种方法,您可以将事件发送到任何组件,而无需通过主实例。