Using slot for reusable logic in Vue js V3

59 Views Asked by At

I'm kinda new to Vue js and I'm stuck on a problem. I'm trying to create a component that will be a render less component and will only handle the logic while the rendering would be done by a different component.

From what I've found in Vue js the intended way would be to use slot, so I came up with this code :

NodeRedControllable.vue

<script>
  import debounce from 'lodash/debounce'

  export default {
    name: 'NodeRedControllable',
    props: {
      "node_red_prop": String
    },

    data () {
      return {
        watcher_enable: true,
        value: 0
      }
    },

    mounted() {
      let self = this
      this.$uibuilder.onTopic(self.node_red_prop, function(msg){
        console.log(msg)
        self.watcher_enable = false
        self.value = msg.payload.value
      })
    },

    methods : {
      setValue(value) {
        this.value = value
      }
    },

    watch: {  

      value: debounce(function (newValue, oldValue) {
        if(this.watcher_enable) {
          this.$uibuilder.send({
            payload:{
              "node_red_prop": this.node_red_prop,
              "value": this.value
            }
          })
          console.log(`The ${this.node_red_prop} has changed value from ${oldValue} to ${newValue}`)
        }
        this.watcher_enable = true
      }, 500)

    },

  }
</script>

<template>
  <slot :value="value" :setValue="setValue"/>
</template>

PumpControl.vue

<script>
import NodeRedControllable from "./NodeRedControllable.vue";

  export default {

    components: {
      NodeRedControllable
    },

    props: {
      "pump_label": String,
      "node_red_prop": String
    }

  }
</script>

<template>
  <NodeRedControllable :node_red_prop="node_red_prop" v-slot="{value, setValue}">
      <v-slider :value="value" @update:modelValue="setValue" :label="pump_label"></v-slider>
  </NodeRedControllable>
</template>

The code work nicely except that my slider doesn't get updated when the NodeRedControllable component receive a message in this function :

this.$uibuilder.onTopic(self.node_red_prop, function(msg){
  console.log(msg)
  self.watcher_enable = false
  self.value = msg.payload.value
})

I expected the slider to be update when receiving a message from my node-red server. The problem doesn't come from the logic that handle the reception of the message as the value is correctly displayed in the console. But it is not transferred from the NodeRedControllable component to the slider in the PumpControl.

0

There are 0 best solutions below