英文:
How to create a global component in Nuxt.js 3?
问题
我有一个 Nuxt 3 项目,其中包含多个布局。我想创建一个全局组件,在客户端首次请求我的网站时运行一次。我不希望在用户更改布局时将其卸载。在 Nuxt 3 中是否可能?
以下是全局组件:
<template>
<component is="script" src="https://js.pusher.com/8.0.0/pusher.min.js" />
</template>
<script setup>
onMounted(() => {
console.log('mounted here')
var pusher = new Pusher('APP_ID', {
cluster: 'CLUSTER_ID',
})
var channel = pusher.subscribe('notifications-general')
channel.bind('PATH', function (data) {
console.log('here in execute')
alert(data.notification.body_en)
})
})
</script>
英文:
I have a nuxt 3 project that has multiple layouts. I'd like to create a global component that runs once when the client first requests my site. And I don't want it to unmount when the user changes layouts. Is this possible with Nuxt 3?
Here is the global component:
<template>
<component is="script" src="https://js.pusher.com/8.0.0/pusher.min.js" />
</template>
<script setup>
onMounted(() => {
console.log('mounted here')
var pusher = new Pusher('APP_ID', {
cluster: 'CLUSTER_ID',
})
var channel = pusher.subscribe('notifications-general')
channel.bind('PATH, function (data) {
console.log('here in execute')
alert(data.notification.body_en)
})
})
</script>
答案1
得分: 2
Sure, here is the translated content:
尝试将该逻辑放入 src/app.vue
中,理论上这应该在浏览器关闭之前都不会卸载,对吗?
也许这会起作用?
<template>
<component is="script" src="https://js.pusher.com/8.0.0/pusher.min.js" />
<nuxt-layout>
<nuxt-page />
</nuxt-layout>
</template>
<script setup>
onMounted(() => {
console.log('在此处挂载')
var pusher = new Pusher('APP_ID', {
cluster: 'CLUSTER_ID',
})
var channel = pusher.subscribe('notifications-general')
channel.bind('PATH, function (data) {
console.log('在此处执行')
alert(data.notification.body_en)
})
})
</script>
英文:
Try putting that logic in src/app.vue
, in theory this should never unmount until the browser it's self is closed?
Perhaps this will work?
<template>
<component is="script" src="https://js.pusher.com/8.0.0/pusher.min.js" />
<nuxt-layout>
<nuxt-page />
</nuxt-layout>
</template>
<script setup>
onMounted(() => {
console.log('mounted here')
var pusher = new Pusher('APP_ID', {
cluster: 'CLUSTER_ID',
})
var channel = pusher.subscribe('notifications-general')
channel.bind('PATH, function (data) {
console.log('here in execute')
alert(data.notification.body_en)
})
})
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论