2014-05-17 77 views
5

Javascript代碼:如何使用Vue js中的名稱獲取視圖或組件對象?

var main = new Vue({ 
     el: "#main", 
     data: { 
      currentView: "top", 
     }, 
    }); 

    var topComponent = Vue.component('top', Vue.extend({ 
    template: "#top", 
    })); 

現在,當我訪問main.currentView,我得到 「頂」。但是對於這個字符串'top',我如何獲得組件topComponent

+0

的可能重複的[DOM元素對應vue.js成分](http://stackoverflow.com/questions/26915193/dom-element-to-corresponding-vue-js-component) – jcoffland

回答

7

VueJS guide

儘管道具和活動的存在,有時你可能仍然需要直接訪問一個子組件在JavaScript中。爲此,您必須使用ref爲子組件分配參考ID。例如:

var parent = new Vue({ el: '#parent' }) 
 
// access child component instance 
 
var child = parent.$refs.profile
<div id="parent"> 
 
    <user-profile ref="profile"></user-profile> 
 
</div>

2

這很容易。您只需使用Vue.component即可訪問topComponent

var topComponent = Vue.component('top'); 

現在你有topComponent,你可以用它的方法做很多事情。

cid 
options 
super 
extend 
directive 
filter 
partial 
transition 
component