2016-04-03 7 views
6

私はVue.jsを使ってコンポーネントを作成し、問題なくDOMに挿入します。要素がDOMに配置されると、レンダリングされた高さを知りたいと思います。つまり、offsetHeightを取得したいと考えています。私はそれをする方法を考えることができません - 私は本当に明白な何かを欠場する必要があります。これは私が試したものです:Vue.jsのComponent ElementのoffsetHeightを取得するにはどうすればよいですか?

HTML:

<!-- vue instance --> 
<div id="my-app"> 

    <my-component></my-component> 

</div> 

<!-- component template --> 
<template id="my-component"> 
    <h1>Hello World</h1> 
    <p>Lorem ipsum dolor sit amet.</h1> 
    <pre>{{ myheight }}</pre> 
</template> 

VueのJavascriptを:

Vue.component('my-component',{ 
    template: '#my-component', 
    computed: { 
     myheight: function(){ 
      return this.offsetHeight; 
     } 
    } 
}); 

Vue({ el: '#my-app' }); 

しかし、それは動作しません - 'myheight' が空終わります。私は多分問題は、DOMに挿入されていた前に計算されたプロパティを生成しようとしているので、代わりに私はこれを試してみました計算されたプロパティを使用するのではされたかもしれないということだと思った:

Vue.component('my-component',{ 
    template: '#my-component', 
    data: function(){ 
     return { 
      myheight: 999 
     }; 
    }, 
    ready: function(){ 
     this.myheight = this.offsetHeight; 
    } 
}); 

ここでも、それはdoesnの何も出力しません。コンソールにエラーや警告が表示されません。

その後、私は多分thisはHTMLElementこのはいないと思ったので、私はVueのドキュメントを検索し、すべてのVueのインスタンスがのHTMLElementを指す$elプロパティを持つべきであることがわかった - あるいは少なくともそれは私がそれを理解する方法です。..私は上記の両方の例でthis.$el.offsetHeightを使ってみましたが、やはり成功しませんでした。

誰かが正しい方向に向かうことができますか?すべての支援は高く評価されています...

答えて

5

あなたのテンプレートに問題があるようです。 fragment instanceのように見えます。つまり、すべての子供を囲むトップレベルの要素はありません。 $elはあなたが欲しいものを参照していない可能性があるので、代わりにこの

、...

<!-- component template --> 
<template id="my-component"> 
    <h1>Hello World</h1> 
    <p>Lorem ipsum dolor sit amet.</h1> 
    <pre>{{ myheight }}</pre> 
</template> 

...あなたは親要素でコンポーネントをラップできます。

<!-- component template --> 
<template id="my-component"> 
    <div class="my-component"> 
     <h1>Hello World</h1> 
     <p>Lorem ipsum dolor sit amet.</p> <!-- and close the tag correctly --> 
     <pre>{{ myheight }}</pre> 
    </div> 
</template> 

は次に、あなたが得ることができますオフセット高さを使用してthis.$el.offsetHeight

Vue.component('my-component',{ 
    template: '#my-component', 
    data: function(){ 
     return { 
      myheight: 999 
     }; 
    }, 
    ready: function(){ 
     this.myheight = this.$el.offsetHeight; 
    } 
}); 

new Vue({ el: '#my-component' }); 
+0

絶対に正しい - 私はそれがいくつかあることを知っていた事は明らかです!ありがとうございました! –

関連する問題