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.setAttributevnode.component.name只是虚拟代码,不存在这种方式。

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

4

2 回答 2

3

我可以弄清楚:

import Vue from "vue";

Vue.directive("hydrate", {
  inserted: function(el, binding, vnode) {
    console.log(vnode.context.$options.name); // the component's name
  }
});
于 2018-08-23T11:41:50.010 回答
1

我无法使用之前发布的解决方案获取我的单个文件组件的名称,因此我查看了始终设法找到名称的 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

于 2019-03-19T09:23:17.040 回答