Vue 3 Composition API - How to specify a prop in setup() - vue.js

I wrote a "loading state" mixin for Vue 2:
export default {
props: {
loading: {
type: Boolean,
default: false
},
},
data () {
return {
innerLoading: false,
}
},
mounted () {
this.innerLoading = !!this.loading
},
methods: {
startLoading () {
this.$emit('update:loading', this.innerLoading = true)
},
stopLoading () {
this.$emit('update:loading', this.innerLoading = false)
},
},
computed: {
isLoading () {
return !!this.innerLoading
},
isNotLoading () {
return !this.innerLoading
},
},
watch: {
loading (loading) {
this.innerLoading = !!loading
},
}
}
I use this mixin for other components to hold the loading state. For example for forms, buttons, tables etc.
Now, Im trying to rewrite this mixin to composition API style for Vue 3. Ideally, I would like to use my loading composable like this:
// components/Table.vue
import 'useLoading' from 'src/composables/loading'
export default defineComponent({
setup () {
const { startLoading, stopLoading, innerLoading } = useLoading()
// ...
return { startLoading, stopLoading, innerLoading, ... }
}
})
My question:
// How can I define the loading prop inside the setup() function?
props: {
loading: {
type: Boolean,
default: false
},
},
Of course I can define my component like this:
import 'useLoading' from 'src/composables/loading'
export default defineComponent({
props: {
loading: {
type: Boolean,
default: false
},
},
setup () {
const { startLoading, stopLoading, innerLoading } = useLoading();
}
})
But imagine, I have 20 components using this mixin/composable. So I want to define that loading prop only ONCE (like I did in mixin).
Is there a way how to do it with composition API?

you may be able to do something like this
import {withProps, useLoading} from "src/composables/loading";
export default defineComponent({
props: {
...withProps()
},
setup () {
const { startLoading, stopLoading, innerLoading } = useLoading();
}
})
where withProps is a function that would have your definitions
export const withProps = () => ({
loading: {
type: Boolean,
default: false
},
})
of course it doesn't need to be a function, but in some cases it may be helpful and preemptively making it a function can make api consistent.

Define an Object called loadingProps in separate file called makeLoadingProps:
export const loadingProps = {
loading: {
type: Boolean,
default: false
}
}
then import it inside your component defined using the script setup syntax:
<script setup lang="ts">
import {defineProps} from 'vue'
import { loadingProps } from 'src/composables/makeLoadingProps';
const props = defineProps({
...loadingProps,
//other props
})
const { startLoading, stopLoading, innerLoading } = useLoading(props)
</script>

Related

vue2 composition api why does watch not fire

I hope this is simple.
I have this component called "brands", it's code looks like this:
import {
computed,
defineComponent,
getCurrentInstance,
ref,
toRefs,
watch,
} from "#vue/composition-api";
import { useTrackProductImpressions } from "#logic/track-product-impressions";
import BrandComponent from "#components/brand/brand.component.vue";
import { Brand } from "#/_core/models";
export default defineComponent({
name: "Brands",
components: { BrandComponent },
emits: ["onMore"],
props: {
brands: {
type: Array,
required: false,
default: () => [],
},
hasMoreResults: {
type: Boolean,
required: false,
},
itemsToShow: {
type: Number,
required: false,
},
loading: {
type: Boolean,
required: false,
},
total: {
type: Number,
required: false,
},
},
setup(props) {
const instance = getCurrentInstance();
const { itemsToShow, brands } = toRefs(props);
const count = ref(0);
const skip = computed(() => {
if (!itemsToShow.value) return 0;
return count.value * itemsToShow.value;
});
const more = () => {
count.value++;
instance.proxy.$emit("onMore");
};
console.log(brands);
watch(brands, (impressions: Brand[]) => {
console.log(impressions);
if (!impressions.length) return;
const route = instance.proxy.$route;
useTrackProductImpressions(impressions, route);
});
return {
skip,
more,
};
},
});
As you can see, I have set up a watch on the brands property, so that when it's defined it will track it. The problem is, it never gets called.
The first console log, I can see the brands ref and can see it's value is an array, but in the watch method, it never gets invoked.
The component is never initialised without brands:
<brands
:brands="brands"
:hasMoreResults="brandsHasMoreResults"
:itemsToShow="brandsItemsToShow"
:total="brandsTotal"
#onMore="brandsFetchMore()"
v-if="brands.length"
/>
Any help would be appreciated.

Vue dynamic component template not working for promise

<template>
<component :is="myComponent" />
</template>
<script>
export default {
props: {
component: String,
},
data() {
return {
myComponent: '',
};
},
computed: {
loader() {
return () => import(`../components/${this.component}`);
},
},
created() {
this.loader().then(res => {
// components can be defined as a function that returns a promise;
this.myComponent = () => this.loader();
},
},
}
</script>
Reference:
https://medium.com/scrumpy/dynamic-component-templates-with-vue-js-d9236ab183bb
Vue js import components dynamically
Console throw error "this.loader() is not a function" or "this.loader().then" is not a function.
Not sure why you're seeing that error, as loader is clearly defined as a computed prop that returns a function.
However, the created hook seems to call loader() twice (the second call is unnecessary). That could be simplified:
export default {
created() {
// Option 1
this.loader().then(res => this.myComponent = res)
// Option 2
this.myComponent = () => this.loader()
}
}
demo 1
Even simpler would be to rename loader with myComponent, getting rid of the myComponent data property:
export default {
//data() {
// return {
// myComponent: '',
// };
//},
computed: {
//loader() {
myComponent() {
return () => import(`../components/${this.component}`);
},
},
}
demo 2

How to call method in setup of vuejs3 app?

In vuejs3 app I retrieve data from db with axios in method, like :
<script>
import appMixin from '#/appMixin'
import app from './../../App.vue' // eslint-disable-line
import axios from 'axios'
const emitter = mitt()
export default {
name: 'adminCategoriesList',
mixins: [appMixin],
data: function () {
return {
categoriesPerPage: 20,
currentPage: 1,
categoriesTotalCount: 0,
categories: []
}
},
components: {
},
setup () {
const adminCategoriesListInit = async () => {
this.loadCategories() // ERROR HERE
}
function onSubmit (credentials) {
alert(JSON.stringify(credentials, null, 2))
console.log('this::')
console.log(this)
console.log('app::')
}
onMounted(adminCategoriesListInit)
return {
// schema,
onSubmit
}
}, // setup
methods: {
loadCategories() {
...
}
and I got error in browser's console :
Cannot read property 'loadCategories' of undefined
If to remove “this.” in loadCategories call
I got error :
'loadCategories' is not defined
I need to make loadCategories as method, as I need to cal;l it from different places.
Which way is correct ?
Thanks!
You could use composition and options api in the same component but for different properties and methods, in your case the data properties could be defined inside setup hook using ref or reactive, the methods could be defined as plain js functions :
import {ref} from 'vue'
export default {
name: 'adminCategoriesList',
mixins: [appMixin],
components: {
},
setup () {
const categoriesPerPage= ref(20);
const currentPage=ref(1);
const categoriesTotalCount=ref(0),
const categories=ref[])
const adminCategoriesListInit = async () => {
loadCategories()
}
function onSubmit (credentials) {
alert(JSON.stringify(credentials, null, 2))
}
functions loadCategories(){
...
}
onMounted(adminCategoriesListInit)
return {
// schema,
onSubmit,
categoriesPerPage,
currentPage,
categoriesTotalCount,
categories
}
},
the properties defined by ref could be used/mutated by property.value and used in template like {{property}}

How to use this data from Vuex inside the component?

What is the best way to use this data from the Vuex store's Action in the needed component?
import axios from 'axios'
export default {
namespaced: true,
state: {
items: []
},
actions: {
fetchCategories ({state, commit}) {
return axios.get('/api/v1/categories')
.then(res => {
const categories = res.data
commit('setItems', {resource: 'categories', items: categories}, {root: true})
return state.items
})
}
}
}
Component
export default {
components: {
ThreadCreateModal,
ThreadList
},
data () {
return {
...
}
},
computed: {
...
},
created () {
...
},
methods: {
...
}
</script>
Where and how should I use that action for binding the data in this component?
Use mapState by import it from vuex and call it in computed:
computed: {
...mapState(['items']), // if you dont use namespace
...mapState("your_module_name", ['items'] ) // if you use namespace
},
then you can access it by this.items.
However, you can access it directly this.$store.state.items

VueJS - vue-charts.js

I am trying to pass data I fetch from API to vue-chartjs as props, I am doing as in the documentation but it does not work.
Main component
<monthly-price-chart :chartdata="chartdata"/>
import MonthlyPriceChart from './charts/MonthlyPriceChart'
export default {
data(){
return {
chartdata: {
labels: [],
datasets: [
{
label: 'Total price',
data: []
}
]
},
options: {
responsive: true,
maintainAspectRatio: false
}
}
},
components: {
MonthlyPriceChart
},
created() {
axios.get('/api/stats/monthly')
.then(response => {
let rides = response.data
forEach(rides, (ride) => {
this.chartdata.labels.push(ride.month)
this.chartdata.datasets[0].data.push(ride.total_price)
})
})
.catch(error => {
console.log(error)
})
}
}
In response I have an array of obejcts, each of which looks like this:
{
month: "2018-10",
total_distance: 40,
total_price: 119.95
}
Then I want to send the data somehow to the chart so I push the months to chartdata.labels and total_price to chartdata.datasets[0].data.
chart component
import { Bar } from 'vue-chartjs'
export default {
extends: Bar,
props: {
chartdata: {
type: Array | Object,
required: false
}
},
mounted () {
console.log(this.chartdata)
this.renderChart(this.chartdata, this.options)
}
}
console.log(this.chartdata) outputs my chartsdata object from my main component and the data is there so the data is passed correctly to chart but nothing is rendered on the chart.
The documentation says this:
<script>
import LineChart from './LineChart.vue'
export default {
name: 'LineChartContainer',
components: { LineChart },
data: () => ({
loaded: false,
chartdata: null
}),
async mounted () {
this.loaded = false
try {
const { userlist } = await fetch('/api/userlist')
this.chartData = userlist
this.loaded = true
} catch (e) {
console.error(e)
}
}
}
</script>
I find this documentation a bit vague because it does not explain what I need to pass in chartdatato the chart as props. Can you help me?
Your issue is that API requests are async. So it happens that your chart will be rendered, before your API request finishes. A common pattern is to use a loading state and v-if.
There is an example in the docs: https://vue-chartjs.org/guide/#chart-with-api-data