0
votes

I'm building some app using Laravel & Vue, and so far so good, but I'm no expert with Vue. So I have one very "begginers" problem, using live data. So I want to make button that will check if live data is on or off, and if they turn it on, it must refresh data and set liveData state to true. For example: This is my "button" and it's not working as expected, It will change state but data is still no live

<div v-if="liveData">
    <div @click="liveData = false">
        Turn OFF Live data
    </div>
</div>
<div v-else="liveData">
    <div @click="liveData = true">
        Turn On Live data
    </div>
</div>

I have defined state like so:

    data() {
        return {
            liveData: false
        }
    },

And this is my created() function:

created() {
        if(this.liveData){
            window.Echo.channel("addOrder").listen(".order-created", (order) => {
                this.$store.commit("ADD_ORDER", order);
            });
        }

        this.$store.dispatch("GET_ORDERS");
    },

So in this case only button is not working, but if I set state to true it's working perfectly. What do I need to do here? Do I need to make new function to work or?

2

2 Answers

0
votes

Created will only be executed once in your component lifecycle. At this point the value of liveData is always false. If you click on your "button" the value should change but your code inside of created will not be executed once more.

Instead of created you can use an immediate watcher:

watch: {
  liveData: {
    immediate: true,
    handler(val) {
      // your code from created here
    }
}
0
votes

Correct the mistake

<div v-else!="liveData">

<div v-if="liveData">
    <div @click="liveData = false">
        Turn OFF Live data
    </div>
</div>
<div v-else!="liveData">
    <div @click="liveData = true">
        Turn On Live data
    </div>
</div>

or

<div v-else>