从Vue指令访问组件名称

问题描述 投票:1回答:2

我想创建一个自定义Vue指令,让我在我的页面上选择我想要保湿的组件。换句话说,这就是我要归档的内容

  1. 我在服务器上渲染我的Vue应用程序(ssr
  2. 我将指令附加到某些组件,如下所示: <template> <div v-hydrate @click="do-something"> I will be hydrated</div> </template>
  3. 我将我的代码发送给客户端,只有那些具有v-hydrate属性的组件将在客户端上被水合(作为root元素)。

我想大致这样做:

我将创建一个标记和记住组件的指令:

import Vue from "vue";

Vue.directive("hydrate", {
  inserted: function(el, binding, vnode) {
    el.setAttribute("data-hydration-component", vnode.component.name);
  }
});

我的想法是,在我的inserted方法中,将一个数据属性写入服务器呈现的元素,我可以在客户端中读出,然后用我的组件水合。

现在我有两个问题:

  1. 这是一种可行的方法吗?
  2. 如何在el.setAttribute中获取组件名称? vnode.component.name只是虚拟代码,并不存在这种方式。

PS:如果你想知道我为什么只想给我的网站部分补水:这是广告。他们搞乱了破坏Vue的DOM。

vue.js serverside-rendering ssr hydration
2个回答
1
投票

我可以搞清楚:

import Vue from "vue";

Vue.directive("hydrate", {
  inserted: function(el, binding, vnode) {
    console.log(vnode.context.$options.name); // the component's name
  }
});

0
投票

我无法使用之前发布的解决方案获取单个文件组件的名称,因此我查看了总是设法找到名称的vue devtools的源代码。他们是这样做的:

export function getComponentName (options) {
  const name = options.name || options._componentTag
  if (name) {
    return name
  }
  const file = options.__file // injected by vue-loader
  if (file) {
    return classify(basename(file, '.vue'))
  }
}

哪里有options === $vm.$options

© www.soinside.com 2019 - 2024. All rights reserved.