简体   繁体   中英

Vue.js: Element is not defined?

<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>

Whenever I try to display res or response in the console, it displays that the element is not defined. It's getting the data for the server, but not displaying it. Whenever I type res or response in the console,I get: Uncaught ReferenceError: res is not defined at :1:1

The console.log(response) statement works, though.

You are printing result.title and result.description as string literals, you need to put them in mustaches to print them from data:

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

I think your problem is in position html elements. Try this way and I think it should work.

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM