在vuejs中渲染组件

时间:2017-12-25 09:35:17

标签: vue.js axios

我正在尝试渲染一个组件,但是我得到了错误:属性或方法 "笑话"未在实例中定义但未在渲染期间引用。我正在使用爸爸的笑话api通过axios http库获取数据。这是我的代码:



var joke = Vue.component('joke', {
  template: '#joke',
  data() {
    return {
      jokes: []
    };
  },
  created() {
    axios
      .get('https://icanhazdadjoke.com/search', {
        headers: {
          Accept: 'application/json'
        },
        params: {
          limit: 30
        }
      })
      .then(response => {
        this.jokes = response.data.results;
      });
  }
});

new Vue({
  el: '#main'
});

  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>vue Dad JOkes</title>
    <!--styles-->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <!--scripts-->
    <script src="https://unpkg.com/vue@2.1.10/dist/vue.js" charset="utf-8"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <div id="main">
      <joke></joke>
    </div>
    <template id="joke">
      <ul>
        <li v-for="joke in jokes"></li>
        <p>{{joke.joke}}</p>
      </ul>

    </template>


    <script src = "app.js" charset="utf-8"></script>
  </body>
 
  </html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这是html的一个简单问题,您在使用</li>之前结束了{{joke}}

更改

<ul>
  <li v-for="joke in jokes"></li>
  <p>{{joke.joke}}</p>
</ul>

<ul>
  <li v-for="joke in jokes">
    <p>{{joke.joke}}</p>
  </li>
</ul>

以下是您的工作示例:

&#13;
&#13;
var joke = Vue.component('joke', {
  template: '#joke',
  data() {
    return {
      jokes: []
    };
  },
  created() {
    axios
      .get('https://icanhazdadjoke.com/search', {
        headers: {
          Accept: 'application/json'
        },
        params: {
          limit: 30
        }
      })
      .then(response => {
        this.jokes = response.data.results;
      });
  }
});

new Vue({
  el: '#main'
});
&#13;
  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>vue Dad JOkes</title>
    <!--styles-->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <!--scripts-->
    <script src="https://unpkg.com/vue@2.1.10/dist/vue.js" charset="utf-8"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <div id="main">
      <joke></joke>
    </div>
    <template id="joke">
      <ul>
        <li v-for="joke in jokes">
          <p>{{joke.joke}}</p>
        </li>
      </ul>

    </template>


    <script src = "app.js" charset="utf-8"></script>
  </body>
 
  </html>
&#13;
&#13;
&#13;