[Vuejs]-How to update Vuejs2 page content when changing select option on api rxjs observable api endpoint?

0👍

Seems like what you’re looking for is a Watcher.

This is most useful when you want to perform asynchronous or expensive
operations in response to changing data.

That’s exactly the case!

Check out the example below I prepared for you using the JSONPlaceholder API.

var app = new Vue({
  el: '#app',
  data: {
    postID: '',
    loading: false,
    postContent: null,
  },
  watch: {
    postID: function () {
      this.fetchPost()
    }
  },
  methods: {
    fetchPost: function(id) {
      this.loading = true;
      fetch('https://jsonplaceholder.typicode.com/posts/'+this.postID)
        .then(response => response.json())
        .then(json => {
          this.postContent = {
            title: json.title,
            body: json.body
          }
          this.loading = false;
        })
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <select v-model="postID">
      <option value="" disabled>Select a post</option>
      <option value="1">Post #1</option>
      <option value="2">Post #2</option>
      <option value="3">Post #3</option>
      <option value="4">Post #4</option>
      <option value="5">Post #5</option>
    </select>
    <h2 v-if="loading">Loading...</h2>
    <div v-if="postContent" class="post_content">
      <h3>{{postContent.title}}</h3>
      <p>{{postContent.body}}</p>
    </div>
</div>

As you can see, the watcher watches for any changes of that property and perform whatever you told it to do. In this case, call the fetchPost method and perform a fetch.

Leave a comment