Making a vuetify autocomplete with composition api and remote api? - vuetify.js

The problem is the following :
How do you manage to make an API call, using Vuetify autocomplete and the brand new composition api ?

It doesn't seem that different from Vue 2.
in main.js
import Vue from 'vue'
import VueCompositionApi from '#vue/composition-api'
import Vuetify from 'vuetify'
import App from './App.vue'
Vue.use(Vuetify)
Vue.use(VueCompositionApi)
Vue.config.productionTip = false
new Vue({
vuetify: new Vuetify({}),
render: h => h(App)
}).$mount('#app')
in App.vue
<template>
<div id="app" data-app>
<v-autocomplete
v-model="model"
:items="items"
item-text="first_name"
item-value="id"
label="Select a user..."
/>
</div>
</template>
<script>
import { ref, onMounted } from '#vue/composition-api'
export default {
setup() {
const model = ref(null)
const items = ref()
const getUsers = async () => {
const { data } = await (
await fetch('https://reqres.in/api/users')
).json()
items.value = data
}
onMounted(getUsers)
return {
model,
items,
}
}
}
</script>
I did it in a codesandbox
https://codesandbox.io/s/vuetify-autocomplete-basic-p6q9m?file=/src/components/HelloWorld.vue

Related

how to lazy load elements on demands depending on the page visited?

I am creating a Laravel project which embed many Vue components (using webpack+mix.js).
-In app.js I have:
import './bootstrap';
require('#fortawesome/fontawesome-free/js/all.js');
import Vue from "vue";
import router from './Router'
import store from './Store/index'
import vuetify from './vuetify.js'
import 'vuetify/dist/vuetify.min.css'
window.Vuetify = require('vuetify');
Vue.use(vuetify);
//import cartComponent from "./components/cartComponent";
// import cart from "./components/Cart";
import 'vuetify/dist/vuetify.min.css'
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)
import BTabs from 'bootstrap-vue'
import datePicker from "vue-bootstrap-datetimepicker";
//
Vue.use(datePicker);
Vue.use(BTabs)
const opts = {}
const my_components = document.getElementsByClassName("my-component-class-wrapper");
for (var i = 0; i <= my_components.length+1; i++) {
new Vue({
el: '#app' + i,
vuetify, //not all pages require it !
store, // *********************now store is shared between all the instances
router,
// opts,
components: {
cartComponent: () => import(/* webpackPrefetch: true */"./components/cartComponent"),
addToCart: () => import('./components/addToCart'), //in productDetail: <add-to-cart>
//cartComponent, //cart icon in navbar
cart: () => import('./components/Cart'),//cartDetails page
info: () => import('./components/Info') //info page
},
data: {},
async created() { //if removed the cart icon will disapear
store.dispatch('fetchProducts').then(_ => { //execute fetchProducts in vuex.
}).catch((error) => console.log(error))
},
validations: {}
});
}
I am using looping, so I can share one store between elements.
The problem is the slowness of the webpages to finish loading. And I discovered that #app0,#app1, .etc. are All carried to every page I visit, getting a message saying:Cannot find element: #app1,#app2,...
besides, not all the pages are using vuetify; another point, I don't need to fetch all the products in every page (async created()).
Is there a way to fetch elements on demand depending on the page I visit ? maybe that will solve the slowness of the pages.
The way the vue component are embedded in pages are :
-page1.blade.php :
<body>
<div id="app0" class="my-component-class-wrapper">
<info></info>
</div>
<script defer src="{{ mix('js/app.js') }}"></script>
</body>
-page2.blade.php:
<body>
<div id="app1" class="my-component-class-wrapper">
<add-to-cart></add-to-cart>
</div>
<script defer src="{{ mix('js/app.js') }}"></script>
</body>

vue v-select array of object not showing in select option

laravel project with vue.i install all thing in app js to work v-select, i don't know anyhting is missing in installation or not.if something is missing tell me that or somthing is wrong in v-select tag please help if anyone is experienced such a thing
on app.js-----------------------------------------------------------------
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router'
import Cat from './components/dashboard/category/Category.vue';
import Sub from './components/dashboard/sub-category/sub-category.vue';
import Dash from './components/dashboard/Dashboard.vue';
import VueToast from 'vue-toast-notification';
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css';
import VModal from 'vue-js-modal';
// import Vue from 'vue';
import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
// Import one of available themes
import 'vue-toast-notification/dist/theme-default.css';
import { Form, HasError, AlertError } from 'vform';
window.Form = Form;
// import {routers} from './routers';
Vue.use(Vuetify)
Vue.use(VueToast);
Vue.use(VueRouter);
Vue.use(VModal);
// Vue.use(vSelect)
Vue.component('v-select', vSelect)
const routes = [
{ path: '', component: Dash },
{ path: '/category', component: Cat },
{ path: '/sub-category', component: Sub },
]
const router = new VueRouter({
routes
})
const app = new Vue({
el: '#app',
router,
vuetify: new Vuetify()
});
on component--------------------------------------------------------------------------------
<v-select v-model="select" :items="categories" label="Select" item-text="name" item-value="id" return-object> </v-select>
export default {
data(){
return {
form: new Form({
name:'',
imgUrl:'',
remember: false
}),
categories:[],
select: 'Select',
}
},
mounted(){
this.getCategories()
},
methods:{
getCategories(){
axios.get('sub-category')
.then(res => (
res.data.forEach((value, index) => {
this.categories.push(value);
})
));
}
}
}
Should the items property in the v-select tag not be called options? Source: https://vue-select.org/guide/options.html#options-prop

Vuetify not translating properly data-table

This is the problem:
main.js
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
import { pt } from 'vuetify/es5/locale/pt'
import { Ripple } from 'vuetify/lib/directives'
Vue.use(Vuetify, {
directives: {
Ripple,
},
lang: {
locales: {
pt,
},
current: 'pt',
},
})
const opts = {}
const vuetify = new Vuetify(opts)
new Vue({
router,
store,
vuetify,
mounted() {
this.$vuetify.lang.defaultLocale = 'pt'
this.$vuetify.lang.current = 'pt'
},
}).$mount('#app')
So I´m trying to initialize Vuetify using Portuguese.
The data table that´s being used is printing these error messages in the console:
[Vuetify] Translation key "dataTable.ariaLabel.sortNone" not found, falling back to default
[Vuetify] Translation key "dataTable.ariaLabel.sortNone" not found in fallback
and so on...
Codepen reproducible example: https://codepen.io/adrielwerlich/pen/MWKJaRV
GitHub bug report link: https://github.com/vuetifyjs/vuetify/issues/11676
How can I solve this?

Vue - Axios is not defined

In a Laravel+Vue project i trying to use axios to get a API response. Axios call a Laravel endpoint and get controller response.
The code looks
JS
require("./bootstrap");
import Swal from "sweetalert2";
import VueI18n from "vue-i18n";
import VueRouter from "vue-router";
import axios from "axios";
import Vuetify from "vuetify";
import es from "vuetify/es5/locale/es";
import en from "vuetify/es5/locale/en";
import "#mdi/font/css/materialdesignicons.css";
import ContadoresComponent from "./components/ContadorComponent.vue";
import GatewaysComponent from "./components/GatewayComponent.vue";
import MainComponent from "./components/MainComponent.vue";
const routes = [{
path: "/",
name: "principal",
component: MainComponent
},
{
path: "/contadores",
name: "contadores",
component: ContadoresComponent
},
{
path: "/gateways",
name: "gateways",
component: GatewaysComponent
}
];
window.Vue = require("vue");
Vue.use(Vuetify);
Vue.use(VueRouter);
Vue.use(VueI18n);
Vue.use(axios);
Vue.component(
"drawer-component",
require("./components/DrawerComponent.vue").default
/* methods: {
changeLocale (lang) {
this.$vuetify.lang.current = lang
},
},*/
);
Vue.component(
"table-component",
require("./components/TableComponent.vue").default
);
export default new Vuetify({
icons: {
iconfont: "mdi"
},
lang: {
locales: {
es,
en
},
current: "es"
}
});
const router = new VueRouter({
routes
});
new Vue({
vuetify: new Vuetify(),
router
}).$mount("#app");
Vue (Vuetify)
<template>
<v-container class="fill-height" fluid>
<v-row align="center" justify="center">
<v-card class="mx-auto">
<v-list-item>
<v-list-item-content>
<v-list-item-title class="headline">Contador</v-list-item-title>
</v-list-item-content>
</v-list-item>
<table-component></table-component>
</v-card>
</v-row>
</v-container>
</template>
<script>
axios.get("/contadores").then(response => console.log(response));
</script>
The error: Return axios is not defined, but i think that i defined in App.js file.
Anybody see the error?
You still need to import it in the second file. You scrip tag should look like this:
<script>
import axios from 'axios';
axios.get("/contadores").then(response => console.log(response));
</script>
You have not imported axios in your file.
To solve this issue either import it in your file where you want to use it as below
import axios from 'axios';
OR
If you don't want to import it in each component where you use it, you can add it to the Vue prototype:
window.axios = require('axios');
//... configure axios...
Vue.prototype.$http = window.axios;
Then in any component you can use
this.$http.post('event/store', {
'name': this.name,
})
An interesting approach that I use in my projects, is to use the library vue-axios, which is very simple to be installed. In case you need to install the dependencies in your project through the commands npm install --save axios vue-axios and then import it into the main.js file or the main file of your application:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use (VueAxios, axios)
The use of axios in the component will be through this.axios.get(`${url}`). Another approach already exposed by friends here at StackOverflow is to import the axios directly into the component you want to use:
<template>
<div>
...
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'ComponentName',
   methods: {
      async getAsyncApi() {
try {
         const result = await axios.get(`${url}`);
} catch(e) {
window.console.error('Error! ', e.message);
}
      },
      getApi() {
         let result;
axios.get(`${url}`).then((r) => {
result = r;
}).catch(e => window.console.error('Error! ', e.message));
      },
   },
};
</script>
I fix the error with
export default {
mounted() {
axios
.get("ENDPOINT")
.then(response => console.log(response));
}
};

Vue.js router view no components?

I am trying to make a vue SPA using vuex, vue-router & laravel for backend. I was separating our data on our app.js to try to reduce clutter and keep our code neat. When everything on one page it works as intended, loading the routes in the router. But when we separate the code to make it more modular into: app.js, boostrap.js, routes.js, and store.js
The components aren't loading in our router-view and we are able to see our RouterLink
app.js
// Require the bootstrapper
require('./bootstrap');
// Grab imports
import Store from './store';
import Router from './routes';
// Views
import App from './views/App';
// Create the application
const app = new Vue({
el: '#heroic',
components: { App },
store: Store,
router: Router
});
boostrap.js
// Imports
import Vue from 'vue';
import Axios from 'axios';
import Swal from 'sweetalert2';
// Add to window
window.Vue = Vue;
window.Axios = Axios;
// Add Axios headers
window.Axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.Axios.defaults.headers.common['Authorization'] = 'Bearer ' + 'token';
window.Axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
routes.js
// Imports
import Vue from 'vue';
import VueRouter from 'vue-router';
import Store from './store';
// Set to use
Vue.use(VueRouter);
// Views
import Hello from './views/Hello';
import Home from './views/Home/';
import UserIndex from './views/UserIndex';
// Create our routes
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/hello',
name: 'hello',
component: Hello,
},
{
path: '/users',
name: 'users.index',
component: UserIndex,
}
];
// Create the router
const router = new VueRouter({
mode: 'history',
routes: routes,
scrollBehavior (to, from, saved) {
if (saved) {
return saved;
}
return { x: 0, y: 0};
}
});
// Before every request
router.beforeEach((to, from, next) => {
});
// After every request
router.afterEach((to, from, next) => {
});
// Export
export default router;
hello.vue
<template>
<div class="row row-cards row-deck">
<div class="col-lg-4 col-md-6">
<p>Hello World!</p>
</div>
</div>
</template>
store.js
// Imports
import Vue from 'vue';
import Vuex from 'vuex';
import PersistedState from 'vuex-persistedstate';
import Cookie from 'js-cookie';
// Set use
Vue.use(Vuex);
// Create our store
const store = new Vuex.Store({
state: {
auth: [{
id: 1,
username: '',
motto: '',
rank: 1,
permissions: [],
token: ''
}],
users: [],
},
mutations:{
},
actions: {
},
getters: {
}
});
// Export
export default store;
The expected result is that when I visit the "/hello" route it would show the information that says "Hello world!" that is within the Vue file specified as the component in the routes section of the router. Instead using my Vue DevTools I get the following with no Hello world on the page.
https://i.pathetic.site/chrome_99Mbxf7f0c.png
My guess is the router is stuck waiting for the beforeEach (and also possibly afterEach) hook to be resolved. You need to call next().
Also unrelated, but if you’re using modules then you shouldn’t need to assign stuff on window.

Resources