我想创建一个自定义Vue
指令,让我在我的页面上选择我想要保湿的组件。换句话说,这就是我要归档的内容
Vue
应用程序(ssr
)<template>
<div v-hydrate @click="do-something"> I will be hydrated</div>
</template>
v-hydrate
属性的组件将在客户端上被水合(作为root
元素)。我想大致这样做:
我将创建一个标记和记住组件的指令:
import Vue from "vue";
Vue.directive("hydrate", {
inserted: function(el, binding, vnode) {
el.setAttribute("data-hydration-component", vnode.component.name);
}
});
我的想法是,在我的inserted
方法中,将一个数据属性写入服务器呈现的元素,我可以在客户端中读出,然后用我的组件水合。
现在我有两个问题:
el.setAttribute
中获取组件名称? vnode.component.name
只是虚拟代码,并不存在这种方式。PS:如果你想知道我为什么只想给我的网站部分补水:这是广告。他们搞乱了破坏Vue的DOM。
我可以搞清楚:
import Vue from "vue";
Vue.directive("hydrate", {
inserted: function(el, binding, vnode) {
console.log(vnode.context.$options.name); // the component's name
}
});
我无法使用之前发布的解决方案获取单个文件组件的名称,因此我查看了总是设法找到名称的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