Javascript 为什么不';t工作$emit和$on?
咖啡脚本:Javascript 为什么不';t工作$emit和$on?,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,咖啡脚本: Vue.component 'levels-list', template: '#levels-list-template' props: ['uuid', 'type'] data: -> { element_levels: [] other_levels: [] } mounted: -> @getElementLevels()
Vue.component 'levels-list',
template: '#levels-list-template'
props: ['uuid', 'type']
data: ->
{
element_levels: []
other_levels: []
}
mounted: ->
@getElementLevels()
return
methods:
getElementLevels: (uuid) ->
if typeof uuid == 'undefined'
uuid = @uuid
_this = this
$.get "/ajax/elements/#{uuid}/element_levels.json", (data) ->
_this.element_levels = []
_this.other_levels = []
$.each data.element_levels, (i, element_level) ->
_this.element_levels.push(element_level)
return
$.each data.other_levels, (i, other_level) ->
_this.other_levels.push(other_level)
return
return
return
switchLevel: (uuid) ->
@getElementLevels(uuid)
levels.$emit('updateBlocks')
return
Vue.component 'article-content',
template: '#article-content-template'
props: ['uuid']
data: ->
{
questions_blocks: []
video_screens: []
}
mounted: ->
@getBlocks()
levels.$on 'updateBlocks', ->
alert 'GOOOOOD'
return
return
methods:
getBlocks: ->
_this = this
$.get "/ajax/elements/#{@uuid}/load_blocks.json", (data) ->
_this.questions_blocks = []
_this.video_screens = []
$.each data.questions_blocks, (i, questions_block) ->
_this.questions_blocks.push(questions_block)
return
$.each data.video_screens, (i, video_screen) ->
_this.video_screens.push(video_screen)
return
return
return
levels = new Vue
el: '#js-levels'
HTML:
此代码显示一个错误:
[Vue warn]:挂载挂钩中出错:(在中找到)
TypeError:undefined不是对象(正在评估“levels.$on”)
为什么会发生此错误?
另外,如果我添加console.log
行:
mounted: ->
@getBlocks()
console.log levels
levels.$on 'updateBlocks', ->
alert 'GOOOOOD'
return
return
我将成功地接收块。但是行
console.log levels
将返回它:undefined
。问题是什么?级别
是未定义的
?在定义之前,您正在访问级别
<代码>级别在脚本底部定义。将其定义向上移动或仅使用this.$on
或this.$emit
。使用this
是推荐的方法(请参阅@evolutionxbox Iflevels
更改为window.levels
并从浏览器控制台调用,但我成功地得到了答案。此外,此代码也能成功运行:switchLevel:(uuid)->console.log levels
@ssc-hrep3我尝试了this
,并且\u this=this
。在这些情况下,没有错误。但是$emit和$on不起作用。@ssc-hrep3我试图实现文档中描述的相同功能。我设法在级别列表
和切换链接
之间建立了连接<代码>开关链接-是参考文档的一个组成部分。简言之,它没有带来任何结果。无法建立与文章内容
组件的交互。
mounted: ->
@getBlocks()
console.log levels
levels.$on 'updateBlocks', ->
alert 'GOOOOOD'
return
return