Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a nested function in vue

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()


                }
like image 320
mots Avatar asked Aug 17 '26 04:08

mots


1 Answers

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>
like image 137
Niklesh Raut Avatar answered Aug 18 '26 20:08

Niklesh Raut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!