Vue.js 2 将数据从组件传递到根实例

Vue.js 2 pass data from component to root instance

我有一个组件发出 AJAX 请求。在回调函数中,我想将一个值传递回父实例或根实例。

所以我在组件中的回调函数是:

function callbackFunc(vm, response){
  vm.$emit('setValue', response.id);
}

在我的根实例中,我试过使用一个名为 setValue 的方法,如下所示:

export default {
  name: 'app',
  data () {
    return {
      value : ''
    }
  },
  methods: {
    setValue: function(value){
      console.log(value);
    }
  }
}

这行不通。文档似乎说你需要在模板中有一个事件才能连接起来,但在这种情况下这是行不通的。

有什么想法吗?

干杯!

I'm using vue-router. So there's the root element that has an App component and then there'sthe component called Hello which has the ajax call

在 parent 组件的模板中,您将有一个 <router-view><\router-view>,vue-router 将放置您的 child。要连接所有内容,您需要将指令添加到模板中:

<router-view v-on:setValue="parentMethod" ><\router-view> 

当child在ajax调用之后调用$emit("setValue")时,会在parent上触发parentMethod()。不清楚您为什么说将其挂接到模板中不起作用。没有模板,就没有真正的 parent/child 关系。