【问题标题】:How to get the view or component object using its name in Vue js?如何在 Vue js 中使用其名称获取视图或组件对象?
【发布时间】:2014-07-06 01:19:27
【问题描述】:

Javascript 代码:

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

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

现在当我访问 main.currentView 时,我得到“顶部”。但是有了这个字符串'top',我如何获得组件topComponent

【问题讨论】:

标签: javascript mvvm viewmodel vue.js


【解决方案1】:

来自VueJS guide

尽管存在 props 和 events,有时您可能仍需要在 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

【讨论】:

    【解决方案3】:

    你可能想看看这个例子:

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

    它使用 html 中的 v-view 指令,该指令接受一个字符串来更改显示的视图模型。一些甜蜜的转变也在发生。

    来自:https://github.com/yyx990803/vue/blob/master/test/functional/fixtures/routing.html

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2018-08-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多