3

I have two functions that are nested in vue, the parent function is supposed to get the value of an attribute, while the child is supposed to use the value of the attribute to make an api call. How can I execute this function once to ensure I get this attribute and make the api call at once?

   //button with the attribute I want
    <button :data-post-id="My id">Click Me</button>
   //Here I'm calling the parent function
        <button @click="getPostId">Submit to api</button> 

Javascript

getPostId: function (evt) {
                    const postId = evt.target.getAttribute('data-postid');
                    //console.log(postId);
                    function usePostId(){
                      console.log("I am accessible here " +postId)//null  
                    }
                    return usePostId()


                }
1
  • 1
    you're probably trying to simply your problem but something is getting lost. recreate your problem here codesandbox.io/s/vue Commented Apr 25, 2018 at 9:01

3 Answers 3

2

Your approach will create function multiple time, Just start with the simple function and keep separate.

new Vue({
  el: '#app',
  data: {
    postid: ''
  },
  methods:{
    setPostId: function (id){
      this.postid = id;
    },
    getPostId: function () {
      console.log(this.postid);
    }
  }
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="app">
  <button @click="setPostId(11)">Set 11</button>
  <button @click="setPostId(22)">Set 22</button>
  <button @click="setPostId(33)">Set 33</button>
  <button @click="getPostId">Get postid</button> 
  <div>{{postid}}</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

I am no vue expert but I can spot one inconsistency.

You are binding your callback to child but set the attr data-post-id on parent and then expecting child to have that attr. Also, it seems the attribute name doesn't match i.e. what you have set and what you are trying to get.

As for the original problem, i am not sure why you didn't add the attribute to child element as well and in case you can't do that you will need to find the desired parent through DOM.

Comments

0

@mots you could do something like the below,

usePostId: function(id) {
  console.log("I am accessible here " + id)
},

getPostId: function(evt) {
  const postId = evt.target.getAttribute('data-post-id')
  const output = this.usePostId(postId)
  return output
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.