vue.js: Error while using v-for

时间:2017-06-07 04:47:48

标签: ajax vue.js

I want to render a table dynamically, based on ajax requests. The Backend is set up properly and when I execute the code the data from the response package is successfully loaded into my variables.

However, when viewing it in the browser, console logs the following error:

[Vue warn]: Failed to generate render function:

SyntaxError: Unexpected token - in

with(this){return _c('div',{attrs:{"id":"app"}},[_m(0),_v(" "),_c('table',[_c('tbody',[_c('tr',_l((header),function(head-item){return _c('th',{domProps:{"textContent":_s(head-item)}})})),_v(" "),_l((data),function(entry){return _c('tr',_l((entry),function(item){return _c('td',{domProps:{"textContent":_s(item)}})}))})],2)])])}


(found in <Root>)

My app.js file:

new Vue({
    el: '#app',
    data: {
        header: [],
        data: [],
    },
    mounted() {
        axios.get('/contacts').then(response => this.load_response(response));
    },
    methods: {
        load_response(response) {
            this.header = response.data.header; 
            this.data = response.data.data;
        }
    }
});

And my html-file:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>TestProject</title>
    <body>
        <div id="app">
            <table>
                <tr>
                    <th>TestHeader/th>
                </tr>
                <tr>
                    <td>TestItem</td>
                </tr>
            </table>
            <table>
                <tr>
                    <th v-for="head-item in header" v-text="head-item"></th>
                </tr>
                <tr v-for="entry in data">
                    <td v-for="item in entry" v-text="item"></td>
                </tr>
            </table>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="/js/app.js"></script>
    </body>
</html>

When I try it in the browser, the first (dummy) table is shown for half a second or so, before it gets hidden. Then the page is blank.

EDIT: The json received from the server is in the form

{
header: [foo, bar, foobar...],
data:[[foo, bar, footer], [foo2, bar2, foobar2], ...]
}

1 个答案:

答案 0 :(得分:4)

您不能在v-for中使用标识符。尝试

<th v-for="headItem in header" v-text="headItem"></th>

对于任何JavaScript变量,Dash都不是valid character