我想要创建一个自定义的Vue指令,允许我在我的页面上选择我想要补充的组件。换句话说,这就是我想要存档的
Vue应用程序(ssr)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。
发布于 2018-08-23 11:41:50
我能搞清楚:
import Vue from "vue";
Vue.directive("hydrate", {
inserted: function(el, binding, vnode) {
console.log(vnode.context.$options.name); // the component's name
}
});发布于 2019-03-19 09:23:17
我无法使用先前发布的解决方案获取我的单个文件组件的名称,所以我查看了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
https://stackoverflow.com/questions/51970741
复制相似问题