如何在Vue.js中正确获取数据

时间:2019-01-20 10:38:34

标签: javascript html vue.js vue-component

这是我的代码,我想获取list数组并将其显示在html

<!DOCTYPE HTML>
<html>
    <head>
        <script src="https://unpkg.com/vue"></script>
    </head>
    <body>

        <div id="app">
            <h2>{{number}}</h2>
            <h2>Here it is!</h2>
            <div v-for="item in list">{{ item.question_text }}</div>
        </div>

    </body>

<script type="text/javascript">

var app = new Vue({
        el: '#app',
        data: {
            number:0,
            list : [{question_text: "apple", question_owner: "HJ", answer_owner: "1Sun"}, 
            {question_text: "banana", question_owner: "HJ", answer_owner: "1Sun"},
            {question_text: "caramel", question_owner: "HJ", answer_owner: "1Sun"},
            {question_text: "demon", question_owner: "HJ", answer_owner: "1Sun"}]

        }
    })

</script>
</html>

enter image description here

我认为Vue被正确识别,但是在获取数据时发生了一些错误,因为四个div DOM元素制作得很好。然后,为什么我不能正确获取数据?

2 个答案:

答案 0 :(得分:0)

尝试将您的 script 标签放入 body header 标签see here

  

它不会在{body>或标记之外validate。也不会   会有很大的不同-除非您要进行DOM操作   可能会破坏IE before的body元素已完全加载-放入它   在结束之前。

答案 1 :(得分:0)

您需要返回数据:

data() {
  return {
    {
      number:0,
      list : [{question_text: "apple", question_owner: "HJ", answer_owner: "1Sun"}, 
        {question_text: "banana", question_owner: "HJ", answer_owner: "1Sun"},
        {question_text: "caramel", question_owner: "HJ", answer_owner: "1Sun"},
        {question_text: "demon", question_owner: "HJ", answer_owner: "1Sun"}]

    }
  }
}