jqueryxmlvue.jsvue-componentvue-resource

Vue.js working with xml feed


I starting working on my personal site using Vue.js. And now i'm suddenly stuck. I want to shot the five newest post om my Jekyll blog on the page.

That's why i'm looking in the http://todayilearned.dk/feed.xmlfeed.

But I can't figure out how to print the three variables in console.log.

How do i do that? (title, link and description.)

I keep getting this error.

data functions should return an object. (found in component: )

  <script>
  var $ = require('jquery');

  export default {
      data: function () {
        $(document).ready(function () {
         var feed = 'http://todayilearned.dk/feed.xml';
         $.ajax(feed, {
           accepts: {
             xml: 'application/rss+xml'
           },
           dataType: 'xml',
           success: function (data) {
             $(data).find('item').each(function () {
               var el = $(this);
               console.log('title      : ' + el.find('title').text());
               console.log('link       : ' + el.find('link').text());
               console.log('description: ' + el.find('description').text());
             });
           }
         });
       });
     }
 };;

The entire code. https://gist.github.com/mikejakobsen/bbe51bef07ae9cdb113501f9025838c7.pibb


Solution

  • You are getting the error because whatever processing you are doing, you should be doing in beforeMount, like following

      <script>
      var $ = require('jquery');
    
      export default {
          data () {
            return {
              title: ''
            }
          },
          beforeMount () {
            var self = this
            $(document).ready(function () {
             var feed = 'http://todayilearned.dk/feed.xml';
             $.ajax(feed, {
               accepts: {
                 xml: 'application/rss+xml'
               },
               dataType: 'xml',
               success: function (data) {
                 $(data).find('item').each(function () {
                   var el = $(this);
                   self.title = el.find('title').text()
                   console.log('title      : ' + el.find('title').text());
                   console.log('link       : ' + el.find('link').text());
                   console.log('description: ' + el.find('description').text());
                 });
               }
             });
           });
         }
     };
    

    beforeMount is one of many Lifecycle Hooks provided by vue where you can access data, computed properties, and methods. You can also choose other hook based on your requirement.

    data is where you define vue instance variable which can be used reactively in the template.