代码之家  ›  专栏  ›  技术社区  ›  Martin Rázus

nuxt js中的自定义指令

  •  6
  • Martin Rázus  · 技术社区  · 6 年前

    有没有一种方法可以在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 warn]:无法解析指令:custom1

    即使在服务器端,它似乎也不起作用。

    谢谢你的建议。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Aldarund    6 年前

    在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>
    
        2
  •  1
  •   AitorDB    6 年前

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

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

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

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