antoniandre / wave-ui

A UI framework for Vue.js 3 (and 2) with only the bright side. ☀️
https://antoniandre.github.io/wave-ui
MIT License
546 stars 41 forks source link

How to access this.$waveui in Vue 3 setup() function? #58

Closed djmattyg007 closed 2 years ago

djmattyg007 commented 3 years ago

How are we supposed to access this.$waveui when using the composition API setup() function? I know you can't refer to this directly in setup(), but it also doesn't seem to work in computed functions either.

antoniandre commented 3 years ago

Hi @djmattyg007, Yes indeed the setup does not let you use this but only props, and attrs, slots, emit via context. But a computed value should access this.$waveui correctly in client side and should be reactive.

Here is an example https://codepen.io/antoniandre/pen/JjWazPR?editors=1010:

<p>width: {{ width }}</p>
  computed: {
    width () {
      return this.$waveui.breakpoint.width
    }
  }

Let me know if that helps :)

djmattyg007 commented 3 years ago

Computed values are also prepared in the setup() function, using the new computed function:

import { computed } from "vue";

export default {
  setup() {
    const x = computed(() => 2 * 3);
    return { x };
  },
}

Based on my testing, I cannot access this (and by extension, this.$waveui) inside computed() functions.

GMolini commented 2 years ago

$waveui cannot be accesed using the composition api (or i havent found how). there should be a thing like import { useWaveUI } from 'wave-ui'; const waveui = useWaveUI(); like the ones inm vuex, or vue-router. Otherwise i dont see how we could access it through the composition api

SebastienLeonce commented 2 years ago

main.ts

import { createApp, reactive } from 'vue'
import App from './App.vue'
import WaveUI from 'wave-ui'
import 'wave-ui/dist/wave-ui.css'
import '@mdi/font/css/materialdesignicons.min.css'

const app = createApp(App)

const waveui = new WaveUI(app, {})

app.
    provide('waveui', reactive(waveui)).
    mount('#app')

component:

<script setup lang="ts">
    import { inject } from 'vue';

    const WaveUi = inject('waveui') as {
        breakpoint: {
            lg: boolean
            md: boolean
            name: "lg" | "md" | "sm" | "xl" | "xs",
            sm: boolean
            width: number
            xl: boolean
            xs: boolean
        }
    }
</script>

html:

<p>{{ WaveUi.breakpoint.width }}</p>
antoniandre commented 2 years ago

Thanks for your valuable input @SebastienLeonce. If you can confirm this would work for your case @djmattyg007, that would be awesome, and I could add a note in the documentation about it 🚀

antoniandre commented 2 years ago

Hi @djmattyg007,

I've run a few tests in this regard and here is how you access the equivalent of this.$waveui in the setup hook.

Also note 3 things:

Here is a demo: https://codepen.io/antoniandre/pen/zYpBgbm?editors=1010

Hope it makes sense! ;)