在子组件Vue Js中使用父组件数据

时间:2016-12-14 14:30:51

标签: javascript vue.js laravel-spark

我正在使用Laraval Spark,并且在组件中有一个组件。

        OleDbConnection connection = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=\"Excel 8.0;HDR=No;\"", filePath));
        OleDbCommand command = new OleDbCommand();
        DataTable tableOfData = null;
        command.Connection = connection;
        try
        {
            connection.Open();
            tableOfData = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string tablename = tableOfData.Rows[0]["TABLE_NAME"].ToString();
            tableOfData = new DataTable();
            command.CommandText = "Select * FROM [" + tablename + "]";
            tableOfData.Load(command.ExecuteReader());
        }
        catch (Exception ex)
        {
        }

在我的父组件中,我的数据方法中有问题数据:

<parent-component :user="user">

   <child-component :user="user" :questions="questions"></child-component>

<parent-component>

正如您所看到的,我已经向我的子组件添加了问题,希望能够使用该组件中的问题,因为我需要遍历它们。

在我的子组件的js文件中,我有:

props: ['user'],
data(){
    return {
        questions: {
            // these are set in another method in this file
        },
    }
},

但是在尝试使用这些问题时,我得到的默认对象与包含所有信息的用户不同。

这应该如何正确地完成,因为我只是在猜... ...

以下是子组件的js文件:

props: ['user', 'questions'],

2 个答案:

答案 0 :(得分:1)

我认为这是模板编译范围的问题。

您似乎正在使用名为Content Distribution with Slots的内容,但模板变量的范围不正确。

参考:https://vuejs.org/v2/guide/components.html#Compilation-Scope

从页面引用:

  

组件范围的简单经验法则是:

     

父模板中的所有内容都在父作用域中编译;子模板中的所有内容都在子范围内编译。

我假设模板的以下行属于您的根组件:

<div id="app">
    <parent-component :user="user">
       <child-component :user="user" :questions="questions"></child-component>
    <parent-component>
</div>

此处,用户已位于根组件中,因此parent-componentchild-component均可使用。但是,您questions的定义位于parent-component,而不是root

根据上面链接中的编译范围文档,您还应该在根组件中加上questions以及user。否则,您应该将父组件模板移动到其自己的vue文件或父组件定义的模板字符串中。

编辑:清晰可能的解决方案

选项1 :您可以定义根组件,并在其中包含questions以及user

new Vue({
    el: '#app',
    data: {
        user: "test user",
        questions: ["one", "two", "three"]
    }
});

上述根组件将userquestions同时提供parent-componentchild-component

选项2 :您可以避免使用带插槽的内容分发,而是使用模板字符串:

Vue.component("parent-component", {
    template: `
        <child-component :user="user" :questions="questions"></child-component>
    `,
    props: ["user"],
    data: function() {
        return {
            questions: {} // You can initialize this in a local method here
        }
    }
    // ...
})

现在,您的child-componentthis.questions属于parent-component

答案 1 :(得分:0)

   questions: {
        // these are set in another method in this file
    }

您想要使用计算属性。

computed: {
  questions(){ return this.anotherMethodInThisFile() }
},
methods: {
  anotherMethodInThisFile(){ return /* many questions */ }
}

然后改变方法以返回问题列表而不是更改组件数据,您就完成了。模板是正确的,你只需把逻辑放在稍微错误的地方。

相关问题