【问题标题】:Passing data to child view将数据传递给子视图
【发布时间】:2019-11-01 12:14:27
【问题描述】:

我正在尝试创建单页应用程序,并希望将数据传递给子视图。

我通过 Axios 读取 API,可以登录到控制台读取。但是,在子视图中渲染数据时,我得到错误“[Vue 警告]:属性或方法“输出”未在实例上定义,但在渲染期间引用。确保此属性是反应性的,无论是在数据选项中,或者对于基于类的组件,通过初始化属性。参见:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。"

app.js
/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';


import '../../node_modules/nprogress/nprogress.css';

const axios = require('axios');


Vue.use(VueRouter);



const app = new Vue({
    el: '#app',

    data: function() {
        return {
            outputs: []
        }
    },


    mounted() {
        axios.get('/api/output')
            .then((response) => {
                this.outputs = response.data;
                console.log(this.outputs);
            })
            .catch((err) => {
                console.log(err);
            });



    },

    router:new VueRouter(routes),

});
Outputs.vue
<template>
    <div><div class="text-grey-darkest font-normal uppercase text-3xl font-bold leading-none mb-3">Outputs</div>
    <ul>
        <li v-for="(journal_id) in outputs" v-text="journal_id"></li>

    </ul>
    </div>
</template>

<script>

    export default{};
</script>

数据结构 JSON

在子视图中以 Li 形式呈现数据。

【问题讨论】:

  • 你应该将子组件中的父数据作为道具传递,而不是像那样引用它

标签: javascript vue.js


【解决方案1】:

数据需要添加到组件中,而不是基本的 Vue 实例。

例如,在Outputs.vue

<template>
    <div>
        <div class="text-grey-darkest font-normal uppercase text-3xl font-bold leading-none mb-3">Outputs</div>
        <ul>
            <li v-for="(journal_id) in outputs" v-text="journal_id"></li>
        </ul>
    </div>
</template>

<script>
    const axios = require('axios');

    export default {
        data() {
            return {
                outputs: [],
            };
        },
        mounted() {
            axios.get('/api/output')
                .then((response) => {
                    this.outputs = response.data;
                })
                .catch((err) => {
                    console.log(err);
                });
        }
    }; 
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2017-09-02
    • 2013-08-16
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多