V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
matts8023

如何通过 vue 实例访问 vue 路由当前显示的单页里的方法?

  •  
  •   matts8023 · Jul 11, 2017 · 3211 views
    This topic created in 3213 days ago, the information mentioned may be changed or developed.

    由于项目需要,用了 SPA 方式进行开发,使用的是 webpack + vue-loader + vue + vue-router。概要代码如下:

    // main.vue
    <template>
      <router-view ref="routerInstance"></router-view>
    </template>
    
    
    // index.vue
    <template>
      <h>Index!!!</h>
    </template>
    <script>
    export default {
      methods: {
        callFromOutside() {
           alert()
        }
      }
    }
    </script>
    
    
    // router.js
    module.exports = {
      routes: [{
        name: 'Index',
        path: '/',
        component: require('./index.vue')
      }]
    }
    

    如果想从 vue 实例对象访问 index.vue 里的 callFromOutside,假设是 vue 实例变量为 vm,同时当前路由页是 Index,则直接调用:

    vm.$refs.routerInstance.callFromOutside()
    

    会提示 undefined。请问这里是哪里出问题了?

    1 replies    2017-07-12 07:13:23 +08:00
    klausgao
        1
    klausgao  
       Jul 12, 2017 via iPhone
    公共方法就直接封装进一个 base.js 啊,然后 import 进来就可以用了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3261 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 14:07 · PVG 22:07 · LAX 07:07 · JFK 10:07
    ♥ Do have faith in what you're doing.