Add custom errors to vee validator(ErrorBag) - vue.js

Is it possible to add custom errors into the ErrorBag
I am using nuxtjs. i have registered vee-validate into my plugin via nuxt.config.js
It works fine However
I want to use the same error code within the template
ex:
<template>
<div v-if="errors.all().length>0">
//loop through
</div>
</template>
i am using axios to fetch user information.
if the request doesnt return my expected data set. i was thinking i could simply
this.errors.push('this is my error message') //-> or some variant of this
When i do this i get that this.errors.push is not a function
I know that
this.errors = ErrorBag{ __ob__: Observer} //-> has items and a vmId attributes
If i amend the code to push onto ErrorBag i get push of undefined

It is documented in the API of ErrorBag. You can add custom messages such as:
// For example, you may want to add an error related to authentication:
errors.add({
field: 'auth',
msg: 'Wrong Credentials'
});
Check the documentation here for more info: https://vee-validate.logaretm.com/v2/api/errorbag.html

Related

In Vuejs, remove the object values in URL after passing object in router query?

<button class="viewButton body" #click="this.$router.push({ name: 'Staff Profile', query:{obj: JSON.stringify(sdList[s.staff_id-1])} })">More Details ></button>
Desire output: To remove the information after obj (refer to the image above) --> /staffProfile?obj
This is what I have tried to do in order to remove but cannot get it working:
<button class="viewButton body" #click="this.$router.push({ name: 'Staff Profile', query:{obj: JSON.stringify(sdList[s.staff_id-1]), as: "/staffDetails"} })">More Details ></button>
You can use history.replaceState() to change the URL without navigating. Place this in the created hook of the page you're loading:
created() {
history.replaceState(history.state, "", "/staffProfile");
}
downsides include losing the query params if you manually reload the page or while manually navigating back to the previous page then forward. Only when clicking your button will the page load with the query params intact. If you need an alternative solution that always preserves this data, you might want to look into saving the query params using a state management library (Vuex or Pinia), or the browser's localStorage API

undefined data error on page reload Nuxt.js

I'm currently developing a universal app using Nuxt.js, the data on most of the pages is retrieved from an API using a fetch hook as well as vuex store. I started noticing errors on page reload/refresh and sometimes when I visit a page from the navbar. The page error is:
TypeError: Cannot read property 'data' of undefined
where data is an object retrieved from an API. I have searched around the internet for this and found it has something to do with data not being loaded or page rendering whilst the data is not fully retrieved. i have found a work around by using a v-if on my template to check if the data is set then display the contents. my question is if there is a way to achieve this, i have tried using the async/await keywords but it doesn't help and i feel like the v-if method is not the best way to handle it.
edit: solved by using $fetchState.pending when using fetch()
If in your template you display right away the data you retrieve from the API, then indeed using the v-if is the right way to do.
If you are using the new fetch() hook, then in your template you can use $fetchState.pending to check if the loading has finished, for example:
<div v-if="$fetchState.pending">
<p> Content is loading... </p>
</div>
<div v-else>
<p> Content has loaded! {{data}}</p>
</div>
<script>
export default{
data(){
return{
data: null
}
}
async fetch(){
this.data = await getSomeAPI
}
}
</script>

Dynamically add json content with vue-if and other vue attributes

I am working chrome extension which uses vue. I have found that google can take a while to publish updates, so there is some content that I would like to be able to edit with a json that is called by the extension via a $.getJSON https request. So far, that has worked pretty well for getting raw text. But I have problems when I try to add a span tag with a v-if statement such as the following:
Thank you for meeting. We have prepared the following <span v-if='docCount.length > 0'>documents</span><span v-else>document</span> for you today:
What happens is that it just says "prepared the following 'documentsdDocuments'" as if it takes all to be true.
I have gotten this result after putting the above JSON text in a v-html as follows:
<p v-html="coverLetterContent['p1']"></p>
I have gotten the same result after trying the following:
.bind(this)).then( function (result){
$(".letter-body").append("<p>"+result["letter"]["p1"]+"</p>")
});
I also tried creating a dynamic component as follows but was getting an error and nothing was rendered:
dynamicComponent: function() {
return {
template: `<p>${coverLetterContent["p1"]}</p>`,
methods: {
someAction() {
console.log("Action!");
}
}
}
}
The error I got on this was: "ReferenceError: coverLetterContent is not defined." coverLetterContent is defined in the vue app data and is accessible via the v-html call described above.

Load a different page in nuxt at runtime based on the parameters in the route

We have a scenario in which a different page is required to be loaded based on whether parts of the route has parameters that are valid and that can be determined at run-time.
Consider the following example:
Request to http://example.com/param1/param2
If param1 is a valid product identifier (can be determined by an API call to another service) the product page loads or its considered a category and Category Page is loaded.
Considering Nuxt uses static routes mostly and the list of products are dynamic, is there a hook where you can execute custom code to load a different page ?
Cant you create _product page
like described in nuxt docs:
https://nuxtjs.org/guide/routing/#dynamic-routes
And in your code make something like:
<template>
<div>
<nuxt-child />
</div>
</template>
<script>
export default {
asyncData({route, params, redirect}) {
//use route
console.log(route.params.slug)
//directly use params
console.log(params.slug)
redirect(`/`);
},
};
</script>
or use mounted() hook if you are creating SPA

vue: Uncaught TypeError: Cannot read property ... of undefined

I'm using vue#2.1.3 and the vue official webpack template to build an app.
When developing locally, I often see the warning Uncaught TypeError: Cannot read property ... of undefined, but the HTML can be rendered successfully. However, the HTML can't be rendered when it's deployed to Netlify with npm run build command. So I have to treat this warning seriously.
I learned from here that it's because "the data is not complete when the component is rendered, but e.g. loaded from an API." and the solution is to "use v-if to render that part of the template only once the data has been loaded."
There are two questions:
I tried wrap v-if around multiple statements that's generating the warning but personal I think this solution is verbose. Is there a neat approach?
"warnings" in local development turn into "fatal errors"(HTML can't be rendered) in production. How to make them the same? e.g. both of them issue warnings or errors?
Just use v-if on a common parent to all the elements in your template relying on that AJAX call, not around each one.
So instead of something like:
<div>
<h1 v-if="foo.title">{{ foo.title }}</h1>
<p v-if="foo.description">{{ foo.description }}</p>
</div>
Do
<div>
<template v-if="foo">
<h1>{{ foo.title }}</h1>
<p>{{ foo.description }}</p>
</template>
</div>
have you tried to initialize all the data you need? e.g. if you need a b c, you can do:
new Vue({
data: {
a: 1,
b: '',
c: {}
},
created(){
// send a request to get result, and assign the value to a, b, c here
}
})
In this way you wont get any xx is undefined error
Guys are right but I can add something.
If there is possibility that your root element in the condition can be undefined for some reason, it is good practice to use something like that: v-if='rootElement && rootElement.prop'. It will secure you from getting cannot get property prop of undefined as when rootelement is undefined, it will not go further in checking.
2021 vue3
we can use like this
props: {
form: {
type: String,
required: true,
},
setup(props, context) {
console.log(props.form)