【问题标题】:Unable to append html element to the parent in Vue js directive无法将 html 元素附加到 Vue js 指令中的父级
【发布时间】:2017-06-18 11:25:36
【问题描述】:

我在 vue js 中有一个全局指令

Vue.directive('customDirective',{
    bind(el,binding,vnode){
        // need to get the parent
        // append a div after the input element
    }
})

我有以下 html 代码。

<div class="parentDiv">
<input type="text" name="firstName" v-customDirective="Some text"/>
</div>

&lt;div class="parentDiv"&gt; is loading dynamically via jquery。我需要获取输入标记的父级,并且需要在输入标记之后附加一些 html。我尝试过使用 parent(),但它显​​示为 parent 不是函数。有什么建议吗?

【问题讨论】:

  • parentDiv 何时添加到 DOM? Vue创建后?

标签: vue.js vuex


【解决方案1】:

如果你想访问父元素,你应该使用inserted 钩子而不是bind

您可以通过el.parentElement获取父元素。

【讨论】:

    【解决方案2】:

    您可能应该使用 vnode 和 Vue nextTick。

    import Vue from 'vue';
    
    Vue.directive('customDirective',{
        bind(el,binding,vnode){
            Vue.bextTick(() => {
                let parent = vnode.elm.parentElement;
            });
        }
    })
    

    如果要使用 jQuery 函数 parent(),则必须通过 jQuery 获取元素。

    Vue.directive('customDirective',{
        bind(el,binding,vnode){
            Vue.bextTick(() => {
                let id = vnode.elm.id;
                let parent = jQuery('#'+id).parent();
            });
        }
    })
    

    我不确定,第二个代码是否有效,但会是这样。

    【讨论】:

      猜你喜欢
      • 2015-08-13
      • 1970-01-01
      • 2012-12-01
      • 2018-01-02
      • 1970-01-01
      • 2015-10-11
      • 2017-05-26
      • 1970-01-01
      • 2016-04-15
      相关资源
      最近更新 更多