在VueJS 2中将事件广播到嵌套路由

时间:2017-09-27 04:47:19

标签: vue.js vue-router

我有以下路线

<script>
  routes = [
    {
      path: '/',
      component: Home,
      children: [{
          path: 'nested1',
          name: 'nested1',
          component: Nested1,
        }, {
          path: 'nested2',
          name: 'nested2',
          component: Nested2,
        }
      ]
    }
  ];
</script>

这是我的Home.vue

<template>
  <div class="wrapper">
    <div class="toolbar">
      <div class="toolbar-actions">
        <el-button :plain="true" type="info" @click="goBack" size="small" icon="arrow-left">Back</el-button>
        <el-button type="success" @click="onSubmit" size="small" icon="check">Submit</el-button>
      </div>
    </div>

    <el-row>
      <el-col :span="4">
        <div class="sidemenu-wrapper">
          <el-menu :router="true" default-active="0" class="sidemenu" ref="sidemenu">
            <el-menu-item index="0" :route="{name: 'nested1'}">nested 1</el-menu-item>
            <el-menu-item index="1" :route="{name: 'nested2'}">nested 2</el-menu-item>
        </div>
      </el-col>

      <el-col :span="20">
        <router-view></router-view>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
    }
  },
  methods: {
    onSubmit() {
      // here I want to be able run certain method in 
      // child route
    },
  }
};
</script>

Nested1.vue

<template>
  <div class="wrapper">
    <el-row>
      <el-col :span="4">
        <el-from>
          <!-- inputs, selects, etc -->
        </el-from>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      // bla bla bla
    }
  },
  methods: {
    submit() {
      // send data to backend 
    },
  }
};
</script>

我想通过单击Home中的“提交”按钮找到执行Nested1的submit方法的方法。可能吗?

1 个答案:

答案 0 :(得分:0)

Home.vue更改此行:

<router-view :ref="routerView"></router-view>

并调用此方法在submit中执行Nested1

this.$refs.routerView.submit()