从精简的组件触发事件并从包含页面的

时间:2018-11-28 06:43:20

标签: svelte svelte-component

我的组件中的代码与example in the svelte docs基本相同:

export default {
  methods: {
    assessmentMouseover(e) {
      const event = new CustomEvent('assessment-mouseover', {
        detail: 'something',
        bubbles: true,
        cancelable: true,
        composed: true, // makes the event jump shadow DOM boundary
      })
      this.dispatchEvent(event)
    },
  },
  ...
}

然后,我将这些代码存储在HTML页面的script标签中,该代码实例化了此组件,该组件也与svelte docs基本上相同:

const el = document.querySelector('#radar')
el.addEventListener('assessment-mouseover', event => {
  console.log('got here')
})

但是,当我触发事件时,出现以下错误:this.dispatchEvent is not a function

我已经在this.dispatchEvent()上尝试了多种变体,例如简单的dispatchEvent(),它不会出错但也不会触发侦听器;和window.dispatchEvent()也无法触发。

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

工作案例代表:https://svelte.technology/repl?version=2.15.3&gist=7b0b820ce452cf6d5d10ebf456627651

Test.html:

<button id="{id}" on:mouseover="doMouseOver(event)">
    {isOver}
</button>

<script>
    export default {
        data() {
            return {
                isOver: 'Over Me!'
            }
        },

        methods: {
            doMouseOver(e) {
                const event = new CustomEvent('assessment-mouseover', {
                    detail: Math.random(),
                    bubbles: true,
                    cancelable: true,
                    composed: true, // makes the event jump shadow DOM boundary
                })

                //this.dispatchEvent(event)

                let source = e.target || e.srcElement
                source.dispatchEvent(event)
            }
        }
    }
</script>

App.html:

<h1>From Test: {text}</h1>

<Test id="radar"/>


<script>
    export default {
        components: {
            Test: './Test.html'
        },

        data() {
            return {
                text: 'Wait for over'
            }
        },

        oncreate() {
            const el = document.querySelector('#radar')
            el.addEventListener('assessment-mouseover', event => {
                this.set({text: event.detail})
            })
        },
    }
</script>