2014-05-17 79 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