nuxt js中的自定义指令

新手上路,请多包涵

有没有办法在 nuxt js 中编写自定义指令,它适用于 ssr 和前端(甚至仅适用于 ssr)?

我在以下文档中尝试过它: https ://nuxtjs.org/api/configuration-render#bundleRenderer

所以我添加了这段代码:

   module.exports = {
      render: {
        bundleRenderer: {
          directives: {
            custom1: function (el, dir) {
              // something ...
            }
          }
        }
      }
    }

到 nuxt.config.js

然后我在模板中使用它作为:

 <component v-custom1></component>

但它不起作用,它只是抛出前端错误

[Vue 警告]:无法解析指令:custom1

而且它似乎甚至在服务器端也不起作用。

感谢您的任何建议。

原文由 Martin Rázus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

在 nuxt-edge 中测试(它的 nuxt 2.0 将在本月或下个月推出,但它目前非常稳定)。

nuxt.config.js

   render: {
    bundleRenderer: {
      directives: {
        cww: function (vnode, dir) {
          const style = vnode.data.style || (vnode.data.style = {})
          style.backgroundColor = '#ff0016'
        }
      }
    }
  }

页面.vue

 <div v-cww>X</div>

从服务器生成的 html:

 <div style="background-color:#ff0016;">X</div>

原文由 Aldarund 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果你想在 Nuxt 中使用自定义指令,你可以执行以下操作:

  • 在 plugins 文件夹中创建一个文件,例如 directives.js
  • 在 nuxt.config.js 中添加类似 plugins: ['~/plugins/directives.js']

在您的新文件中添加您的自定义指令,如下所示:

 import Vue from 'vue'

Vue.directive('focus', {
  inserted: (el) => {
    el.focus()
  }
})

原文由 AitorDB 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题