Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS accessing components from instance

I am looking for a way to access my component's method from my instance

<button id="live" class="ui primary button" v-on:click.prevent="live">
    Live Text
</button>

which is directly inside my #app and to get it to launch a live method from inside my component Live.vue I've found tons of documentation prior to ver 2.x about broadcast and dispatch, but after hour of trying to get it working using $emit I am not sure what am I doing anymore ..

<template>
  <div v-if="loaded">
    Live
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      loading: false,
      loaded: false,
    }
  },
  methods: {
    load: function (event) {
      console.log('loading..')
      this.loaded = !this.loaded
    }
  },
  mounted: function () {
    // this.$on('liveClick', function (msg) {
    //   console.log(msg)
    // })
  },
  name: 'Live',
  props: {
    'id': Number,
    'key': String
  }
}
</script>

and init.js (it's a laravel based structure)

window.App = new Vue({
   el: '#app',
   methods: {
     live: function (event) {
       this.$emit('liveClick', 'msg')
     }
   }
})

I already did a 'workaround' with Vuex, but I don't need to complicate my learning curve just to get this working.

jsfiddle: https://jsfiddle.net/c4s44qgy/1/

like image 779
dev Avatar asked Jun 03 '26 05:06

dev


1 Answers

You can find fixed fiddle here: https://jsfiddle.net/gr9c6h64/

Basically, when you want to pass data to components from main Vue instance, you have to use props in this component like I made in the fiddle: props: { loaded: String } and then pass value from parent using :loaded='isLoaded'

I don't think it is exactly what you want to do, but it looks like it is what you are having issue with. Hope it helps!

like image 142
Marek Urbanowicz Avatar answered Jun 06 '26 02:06

Marek Urbanowicz



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!