Vue.js nuxt js中的自定义指令

Vue.js nuxt js中的自定义指令,vue.js,nuxt.js,server-side-rendering,Vue.js,Nuxt.js,Server Side Rendering,有没有办法在nuxt js中编写一个自定义指令,它既适用于ssr,也适用于前端(甚至只适用于ssr) 我在以下文档中尝试过: 因此,我添加了以下代码: module.exports = { render: { bundleRenderer: { directives: { custom1: function (el, dir) { // something ... }

有没有办法在nuxt js中编写一个自定义指令,它既适用于ssr,也适用于前端(甚至只适用于ssr)

我在以下文档中尝试过:

因此,我添加了以下代码:

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

  render: {
    bundleRenderer: {
      directives: {
        cww: function (vnode, dir) {
          const style = vnode.data.style || (vnode.data.style = {})
          style.backgroundColor = '#ff0016'
        }
      }
    }
  }
然后我在模板中使用它作为:

<component v-custom1></component>

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

[Vue warn]:无法解析指令:custom1

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


感谢您的建议。

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

  • 在plugins文件夹中创建一个文件,例如directions.js
  • 在nuxt.config.js中添加类似于
    插件:['~/plugins/directions.js']
在新文件中添加自定义指令,如下所示:

import Vue from 'vue'

Vue.directive('focus', {
  inserted: (el) => {
    el.focus()
  }
})
在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'
        }
      }
    }
  }
page.vue

<div v-cww>X</div>
X
从服务器生成的html:

<div style="background-color:#ff0016;">X</div>
X
如何创建指令
通过将扩展名
.client.js
添加到指令文件中,可以使指令在客户端上运行。这适用于
SSR
static
渲染

//插件/directive.client.js
从“Vue”导入Vue
Vue.指令('log-internal-text'{
插入:el=>{
cosole.log(el.innerText)
}
})

如何插入指令 在
numxt.config.js文件中,将其添加为如下插件

插件:[
“~/plugins/directive.client.js”
]
别忘了将指令保存在plugins文件夹中


如何使用指令 你好
控制台日志

> "Hello"

我写了一篇媒体文章,更深入地阐述了这一点。它向您展示了如何制作一个指令,使元素在滚动视图中显示动画:

对于任何其他来到这里的人,接受的答案允许您运行仅SSR指令。如果您想在任何地方都运行指令,这是有帮助的,但有点不直观

如果仅使用nuxt.config.js通过
render
实现指令,则如果不添加指令插件并将其添加到配置中,客户端将不支持该指令(请参见如何创建指令应答)

要测试这一点,请尝试以下实验:

  • 按照说明使用插件创建指令(制作一个称为加载的插件)
  • 将此添加到您的nuxt.config:
在Vue页面文件上使用该指令,如:

<div v-loading="true">Test</div>
测试
在页面加载时,您将看到客户端和SSR指令都在运行。如果删除客户端指令,您将看到抛出的错误,如OP had:
[Vue warn]:无法解析指令:load


在nuxt 2.12.2上测试。

谢谢@Sphinx,但这通常与我粘贴的代码相同,对我不起作用,你没有一些工作示例吗?我现在遇到了与你相同的问题(nuxt.js 1.4.0)。我刚刚尝试了
bundlerender.shoulldpreload
它可以正常工作,但是
bundlerender.directives
没有。谢谢你的提示,但这只在前端工作,对服务器端呈现的html没有任何影响。你如何设置元素的innerText?@TimarIvoBatis尝试一下这个,谢谢哈哈,这是我的问题,也是我的答案:DPS:我还写了一篇关于自定义SSR指令的小文章:
<div v-loading="true">Test</div>