Vue.js:元素没有定义?

时间:2017-06-12 06:09:51

标签: javascript ajax vue.js axios

<body>
<center>
<div id="app">
<h1> News Aggregator </h1>

<div id="selector">
    <select v-model="selected">
        <option v-for="select in selection" :value="select">{{select}}</option>

    </select>
    <button @click="getNews(selected)"> Get news </button>
</div>
</center>


<div id = "news-container" v-for="result in res">
    <h1> result.title </h1>
    <p> result.description </p>
    </div>


</div>

<script>
const API_KEY = "e58c5c8781a44b8e94a4725a4606655c";
const url = "https://newsapi.org/v1/articles?";

const SELECTION = "BBC News,The Times of India,BBC Sport";

const app = new Vue({
    el: "#app",
    data: {
        res : [],
        selection : SELECTION.split(','),
        selected : 'bbc-news',
        response: []
    },
    mounted(){
        this.getNews(this.selected);
    },
    methods: {
        getNews(selected){
            selected = selected.replace(/\s+/g, '-').toLowerCase();
            axios.get(url+"source="+selected+"&sortBy=top&apiKey="+API_KEY).then((response)=>{
            console.log(response);
            this.res = response.data.articles;
            }).catch(function(error){
                console.log(error);
                });
            }
        }
    });

</script>

每当我尝试在控制台中显示res或response时,它都会显示该元素未定义。它正在获取服务器的数据,但不显示它。 每当我在控制台中键入res或响应时,我得到:  未捕获的ReferenceError:未定义res     at:1:1

但是,console.log(响应)语句可以正常工作。

2 个答案:

答案 0 :(得分:0)

您正在将result.titleresult.description打印为字符串文字,您需要将它们放入胡须中以便从数据中打印出来:

<div id = "news-container" v-for="result in res">
  <h1> {{result.title}} </h1>
  <p> {{result.description}} </p>
</div>

答案 1 :(得分:0)

我认为你的问题在于html元素的位置。尝试这种方式,我认为它应该工作。

<body>
<div id="app">
  <h1> News Aggregator </h1>

  <div id="selector">
    <select v-model="selected">
      <option v-for="select in selection" :value="select">{{select}}</option>

    </select>
    <button @click="getNews(selected)"> Get news </button>
  </div>


  <div id="news-container" v-for="result in res">
    <h1> {{result.title}} </h1>
    <p> {{result.description}} </p>
  </div>
</div>
</body>