vue bootstrap toaster instantly vanishing / hiding itself - vue.js

In my Vue Bootstrap (v2.21.2) Web-App i want to use Toasts to present some errors to the user. Those errors are produced by the REST-API-client. In my vb-components i catch those errors and call a function which itself uses https://bootstrap-vue.org/docs/components/toast#toasts-on-demand this.$bvToast.toast() to dynamically create and show the error-message.
As expected the toast is created but will instantly hide itself again. I tried disabling the auto-hide property and play around with the timeout which had no effect. Since i am calling this function in some sub-components i also tried calling this.$root.$bvToaster.toast() but the toasts are still only showing for some 100 microseconds or so.
The relevant (reduced) code-extracts of my project:
App.vue:
<template>
<div id="app">
<Navbar #viewChanged="view = $event;" />
<Pki v-if="view == 'pki'" />
</div>
</template>
<script>
import Navbar from "./components/Navbar.vue";
import Pki from './components/Certificates'
export default {
data() {
return {
view: null
}
},
name: "FooBar",
components: {
Navbar,
Pki
},
};
</script>
Certificates.vue:
<template>
<!-- ... -->
</template>
<script>
// ...
mounted() {
this.getCertificates();
},
methods: {
alert(title, content, variant = 'danger') {
this.$bvToast.toast(content, {
title: title,
toaster: 'b-toaster-bottom-right',
variant: variant,
solid: true,
appendToast: true,
autoHideDelay: 10000
});
},
getCertificates() {
axios.get("/v1/pki/certificates")
.then((response) => {
// ...
});
})
.catch((error) => {
this.alert('API Error', 'failed to fetch certificate list (' + error.message + ')');
console.log('getCertificates(): HTTP ERROR ' + error.response.status + ' (' + error.response.data + ')');
});
}
}
</script>

If you are using bootstrap 5 just add this css
.toast:not(.show) {
display: block;
}

I think you don't have the appropriate version of the bootstrap css.
e.g 4.5.3 bootstrap css
and after load the vue bootstrap
Had the same issue, and this solved it

Related

Vuejs load directive dynamicly via data property

From the axios i am getting <test-component></test-component> and i want to add this as a component to the example-component
The output is now
<test-component></test-component>
In stead off
test component
Is that possible and how can i achieve that?
App.js:
import Example from './components/ExampleComponent.vue'
import Test from './components/Test.vue'
Vue.component('example-component', Example)
Vue.component('test-component', Test)
const app = new Vue({
el: '#app'
});
ExampleComponent:
<template>
<div class="container">
{{test}}
</div>
</template>
export default {
data() {
return {
test: ''
}
},
created() {
axios.get('/xxxx')
.then(function (response) {
this.test = response.data.testdirective
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
}
TestComponent:
<template>
<div class="container">
test component
</div>
</template>
It is not possible with the runtime-only build of vuejs. You will need to configure your setup to use the full build of vuejs. The docs specify the setup with some build tools like webpack.
Once the vue template compiler is integrated in the runtime. You can use your current approach to render the component dynamicaly.
There is also another approach to this, which is a bit simpler.
You can use dynamic components like this:
<template>
<div>
<component v-if="name" :is="name"></component>
</div>
</template>
<script>
import TestComponent from "./TestComponent.vue"
import Test2Component from "./Test2Component.vue"
import Test3Component from "./Test3Component.vue"
export default {
component: {
TestComponent,
Test2Component,
Test3Component
},
data() {
return {
name: undefined
}
},
created() {
axios.get('/xxxx')
.then(function (response) {
// where 'response.data.testdirective' is the components name
// without <> e.g. "test-component", "test1-component" or "test2-component"
this.name= response.data.testdirective
})
.catch(function (error) {
// handle error
console.log(error);
this.name = undefined
})
.finally(function () {
// always executed
});
}
}
</script>
As you can see, instead of compiling the components on the fly, I import them to get pre-compiled and bind them dynamically via name. No additional setup required!

Nuxt JS load components depending on API response

I'm building a nuxt app to consume the wp rest API. In my fetch method I fetch information about needed components. I can't figure out how to then import all the components and render them. I've tried several methods, but I can't see to make it work.
Here's what works:
<component :is="test" :config="componentList[0]"></component><br>
export default {
async fetch({ store, $axios }) {
await store.dispatch("getPageBySlug", "home");
},
computed: {
test() {
return () => import('~/components/HeroIntro');
}
}
};
Ok so this is easy, nothing special - I could now import the component based on the slug etc. But I need to render multitple components and therefor im doing this:
<component
v-for="component in componentList"
:key="component.acf_fc_layout"
:is="component.acf_fc_layout"
:config="component">
</component>
along with this
export default {
async fetch({ store, $axios }) {
await store.dispatch("getPageBySlug", "home");
},
computed: {
page() {
return this.$store.getters.getPageBySlug("home");
},
componentList() {
return this.page.acf.flexible_content;
},
componentsToImport() {
for(const component of this.componentList) {
() => import('~/components' + component.acf_fc_layout);
}
}
}
};
All I'm getting is
Unknown custom element: HeroIntro - did you register the
component correctly? For recursive components, make sure to provide
the "name" option
How do I archieve what im trying?
edit:
So, after a lot of trying, I could only make it work with using an extra component, "DynamicComponent":
<template>
<component :is="componentFile" :config="config"></component>
</template>
<script>
export default{
name: 'DynamicComponent',
props: {
componentName: String,
config: Object
},
computed: {
componentFile() {
return () => import(`~/components/${this.componentName}.vue`);
}
}
}
</script>
Now in Index.vue
<template>
<main class="container-fluid">
<DynamicComponent
v-for="(component, index) in componentList"
:key="index"
:componentName="component.name"
:config="component"
/>
</main>
</template>
<script>
export default {
components: {
DynamicComponent: () => import("~/components/base/DynamicComponent")
}
I am not sure yet if this is optimal - but for now it works great - any input / opinions would be great!

Render and Compile String using vue.js

There is a requirement where all html elements are defined in a JSON file and used in the template.
There is a function - "markComplete" which needs to be triggered on change of a checkbox.
Code Template:
<template>
<span v-html="htmlContent"></span>
</template>
<script>
data(){
return{
htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
}
}
</script>
Above code won't work as onChange event won't be mounted, and I get Uncaught ReferenceError: markComplete is not defined
Is there any way to make this work?
You are trying to compile the string as Vue Templates using v-html.
Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates
Read about v-html in Vue Docs.
As solution you can read this article
You don't want to use a library? Checkout the code below:
First create a js file (preferably RenderString.js):
import Vue from "vue"
Vue.component("RenderString", {
props: {
string: {
required: true,
type: String
}
},
render(h) {
const render = {
template: "<div>" + this.string + "</div>",
methods: {
markComplete() {
console.log('the method called')
}
}
}
return h(render)
}
})
Then in your parent component:
<template>
<div><RenderString :string="htmlContent" /></div>
</template>
<script>
import RenderString from "./components/RenderString"
export default {
name: "App",
data: () => ({
htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
})
}
</script>
Note: I didn't run the code above but I created a similar working CodeSandbox Example

How To run a function in Vuejs after the component in created?

I have created a component which has a function which makes external API calls and then fills an array. I used created() life hook to run the function for the 1st time. I am passing a variable from the parent component into this component and then based upon this variable change I want the function to run again.
How do I achieve this.
Attaching my code below
<template>
<div>
<p>{{ data_to_show_on_mainpage }}</p>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'GetCategoryItemsAndDisplayOne',
props: ['categoriesfordisplay','ismainpage', 'catalogselected'],
data(){
return {
IsMainPage_1 : "",
data_to_show_on_mainpage : [],
}
},
watch: {
catalogselected: function(){
this.GetItemsToShowonMainPage()
}
},
methods:{
changevalue(){
console.log("i am reducing it to emplty after change of catalog")
this.IsMainPage_1 = this.catalogselected
this.data_to_show_on_mainpage = []
},
CatlogService(catlog_name,category,gender,mainpage){
let url = "http://localhost:5000/xyz/" + (this.catalogselected).replace(/'/g,"%27") +"/api/"+ (gender) + "/catalogvis/" + (category) +"/items"
console.log(encodeURI(url))
axios.get(encodeURI(url)).then((resp)=>{
this.data_to_show_on_mainpage.push(resp.data.response.Results.results[0])
})
.catch(err => {
console.log("we got an error the url is " + url)
console.log(err);
})
},
GetItemsToShowonMainPage(){
this.changevalue()
if(this.categoriesfordisplay.men_for_display.length>0){
for(let i =0;i<this.categoriesfordisplay.men_for_display.length;i++){
let category = this.categoriesfordisplay.men_for_display[i].replace(/"/g,"%27");
this.CatlogService(this.catalogselected,category,'men',this.ismainpage)
}
}
if(this.categoriesfordisplay.women_for_display.length>0){
for(let i = 0;i<this.categoriesfordisplay.women_for_display.length;i++){
let category = this.categoriesfordisplay.women_for_display[i].replace(/"/g,"");
this.CatlogService(this.catalogselected,category,'women',this.ismainpage)
}
}
},
},
created(){
this.GetItemsToShowonMainPage()
}
}
</script>
<style>
</style>
How Do i trigger the GetItemsToShowonMainPage() function whenever the catalogselected varaible is changed.
It looks fine.
As #a-lau says, make sure the parent is updating the catalogselected prop
Btw, you can write your watcher this way and remove completely the created hook:
watch: {
catalogselected: {
handler: "GetItemsToShowonMainPage",
immediate: true
}
}
If you still have issues you might want to write a minimal reproduction on https://codesandbox.io/s/vue

VueJS - trigger Modal from materializecss

I am trying to trigger a modal from the materializecss framework within a VueJS-instance.
Both, VueJS and Materializecss, are implemented correct. On their own both frameworks work fine.
Clicking the open-button results in an error:
Uncaught TypeError: data[option] is not a function
at HTMLDivElement. (adminarea.js:24562)
at Function.each (adminarea.js:10567)
at jQuery.fn.init.each (adminarea.js:10356)
at jQuery.fn.init.Plugin [as modal] (adminarea.js:24556)
at Vue$3.showLoader (adminarea.js:21396)
at boundFn (adminarea.js:54956)
at HTMLButtonElement.invoker (adminarea.js:56467)
This is my Vue-Instance:
const app = new Vue({
el: '#app',
data: {
activeUser: {
username: '',
email: ''
},
},
methods: {
showLoader(){
$('#loaderModal').modal('open');
},
closeLoader(){
$('#loaderModal').modal('close');
}
},
mounted() {
// Get current User
axios.get('/api/currentUser')
.then(response => {
this.activeUser.username = response.data.username;
this.activeUser.email = response.data.email;
});
},
components: {
Admindashboard
}
});
And here is the part of my html-file with the modal structure:
<!-- Modal Structure -->
<div id="loaderModal" class="modal">
<div class="modal-content">
<h4>Fetching data..</h4>
<div class="progress">
<div class="indeterminate"></div>
</div>
</div>
</div>
<button class="btn cyan waves-effect waves-cyan" v-on:click="showLoader">Open</button>
Any ideas? Thanks!
It seems I found an solution:
Nice to know for Laravel-users: for my current project I use Laravel 5.5 with Materializecss, VueJS and VueRouter but I think the solution is universal. Materializecss was installed via npm and has to be included into your application. I've required the css-framework within my ressources/assets/js/bootstrap.js:
...// more code
try {
window.$ = window.jQuery = require('jquery');
window.materialize = require('materialize-css');
} catch (e) {
console.log(e);
}
...// more code
Now you have to initialize the Modal-function on the mounted-event of your wrapping Vue-instance:
const app = new Vue({
router,
data: {
...
},
methods: {
testClick: function(){
console.log('Testklick-Call');
$('#modal1').modal('open');
}
},
mounted: function(){
console.log('Instance mounted');
$('.modal').modal();
}
}).$mount('#app');
The code above is placed within my ressources/assets/js/app.js and is packed by default by Laravel Mix but I think this is universal and also usable without Laravel Mix/Webpack etc.
Now you can call every modal programmatically from where ever you want. I've tested it in my main instance on a click-event. Function is placed in my Vue-instance (see above). HTML-Code see below:
<button v-on:click="testClick">Open Modal</button>
But you can also make use of the modal within a mounted-function or any other function of any component:
<template>
<div>
<p>I am an component!</p>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted!');
$('#modal1').modal('open');
}
}
</script>
This also works, if the component becomes only visible after clicked on a link (using VueRouter).
Hopefully this helps someone except me :)
As suggested here, you need to add following code in the mounted block:
mounted() {
$('#loaderModal').modal(); //New line to be added
// Get current User
axios.get('/api/currentUser')
.then(response => {
this.activeUser.username = response.data.username;
this.activeUser.email = response.data.email;
});
},