How to get the view or component object using its name in Vue js?
Asked Answered
S

3

9

Javascript code:

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

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

Now when I access main.currentView, I get "top". But with this string 'top', how do i get the component topComponent?

Steger answered 17/5, 2014 at 18:28 Comment(1)
possible duplicate of DOM element to corresponding vue.js componentEllett
B
13

From the VueJS guide

Despite the existence of props and events, sometimes you might still need to directly access a child component in JavaScript. To achieve this you have to assign a reference ID to the child component using ref. For example:

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>
Bucktooth answered 8/1, 2015 at 4:1 Comment(2)
What about accessing child of third-party component?Movement
is isn't globalOculo
L
8

It's easy. You can access the topComponent just using Vue.component.

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

Now you have topComponent, you can do a lot of things with its methods.

cid
options
super
extend
directive
filter
partial
transition
component
Laicize answered 25/2, 2015 at 11:7 Comment(0)
A
1

You may want to check out this example:

http://jsbin.com/wikeb/1/edit

It uses the v-view directive in the html, which takes a string to change the viewmodel displayed. Some sweet transitions going on as well.

Comes from: https://github.com/yyx990803/vue/blob/master/test/functional/fixtures/routing.html

Ave answered 24/5, 2014 at 13:49 Comment(1)
this exemple works for the old legacy version of vue. I corrected it and here is the update jsbin.com/jizegefape/2Postrider

© 2022 - 2024 — McMap. All rights reserved.