Fill modal with Vue js

Asked

Viewed 219 times

1

The problem:

I’m developing a site that has a feed with publications, each post has comments. When I click on the post comments button, I need to load a modal filled with comments and post.

That part I can do, I just don’t know how to use the watch function to react to data changes, as for example, when commenting on the post (in modal), the observer(watch) adds the comment in the same.

Note: I already tried to use the watch, but since the modal is only filled when the user clicks on the comment button, I don’t know how to "initialize" the empty observer.


Where the data comes from:

The posts are in the store, when clicking on comments, I call a function that passes the post to store and open the modal with comments and publication:

Function that puts the clicked post in the store:

setOnCommentPost: function(post){
            this.$store.commit('setOnCommentPost',post);
            $("#commentPost").modal('show');
        }

Store:

state:{
    posts:{},        //Todos os posts do feed
    onCommentPost:{  //Post que esta atualmente no modal de comentários
        user:{},     //Usuário que postou
        comments:{}
    }
}

Component Script Comments that is inside the modal component:

props:['action','method','user_auth'],
data: function(){
    return{
        post:{
            user:{},
            comments:{}
        }
    }
},
watch:{
    post: function(){
        this.post.comments = this.$store.getters.getOnCommentPost.comments
        this.post = this.$store.getters.getOnCommentPost
        this.post.user = this.$store.getters.getOnCommentPost.user
        this.post.likes = this.$store.getters.getOnCommentPost.likes
    }
}
  • Is Modal a component? Or an isolated component type jQuery? If yes it should fetch the data and the reactivity of Vuex solves the rest... you can show the Modal code?

  • Modal is a component. I added the comment component code (which is in the modal Component slot)

1 answer

0

By default, the watch function observes modifications to an object at a "higher" level, i.e., it observes no internal modifications to the object.

So if you have the object post and change it to some other value, Watcher will identify the modifications, but in your case you modify the internal values of the object post.comments.

So for your Watcher to work you must add the property deep: true as follows

watch: {
  post: {
    deep: true,
    handler() {
      this.post.comments = this.$store.getters.getOnCommentPost.comments
      this.post = this.$store.getters.getOnCommentPost
      this.post.user = this.$store.getters.getOnCommentPost.user
      this.post.likes = this.$store.getters.getOnCommentPost.likes
    },
  },
},

So he starts to observe "internal" modifications to the object as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.