link1096 link1097 link1098 link1099 link1100 link1101 link1102 link1103 link1104 link1105 link1106 link1107 link1108 link1109 link1110 link1111 link1112 link1113 link1114 link1115 link1116 link1117 link1118 link1119 link1120 link1121 link1122 link1123 link1124 link1125 link1126 link1127 link1128 link1129 link1130 link1131 link1132 link1133 link1134 link1135 link1136 link1137 link1138 link1139 link1140 link1141 link1142 link1143 link1144 link1145 link1146 link1147 link1148 link1149 link1150 link1151 link1152 link1153 link1154 link1155 link1156 link1157 link1158 link1159 link1160 link1161 link1162 link1163 link1164 link1165 link1166 link1167 link1168 link1169 link1170 link1171 link1172 link1173 link1174 link1175 link1176 link1177 link1178 link1179 link1180 link1181 link1182 link1183 link1184 link1185 link1186 link1187 link1188 link1189 link1190 link1191 link1192 link1193 link1194 link1195 link1196 link1197 link1198 link1199 link1200 link1201 link1202 link1203 link1204 link1205 link1206 link1207 link1208 link1209 link1210 link1211 link1212 link1213 link1214 link1215 link1216 link1217 link1218 link1219 link1220 link1221 link1222 link1223 link1224 link1225 link1226 link1227 link1228 link1229 link1230 link1231 link1232

[Vue.js] Validate array of inputs with Vee-Validate (Vuejs)

The following works:

<li :key=”index” v-for=”(…) in items”>
<input type=”text” name=”itemFields[]“ v-validate=”required”>
</li>

// …

<div class=”vv-errors”>
<ul>
// shows only for last active input
<li v-for=”error in errors.collect(‘itemFields[]‘)”>{ error }</li>
</ul>
</div>

If I make some input empty, it shows an error message. But if I then fill some other empty input with text, the error message disappears completely. That should not be the case, because the other input is still empty. To summarize, the error messages only consider the last active input.

How to achieve that the error message shows up if at least one of the inputs is empty?

Solution :

Actually the issue you are facing is because the name field is same for all the inputs and that should be unique.
Hence while using v-for you could do something as below :

<div v-for=”i in 5” >
<input type=”text” :name=”‘email’+i” placeholder=”Email” v-validate=”‘required|email’”>
<span class=”error” v-if=”errors.has(‘email’+i)”>{errors.first(‘email’+i)}
</span>
</div>

Here is a basic example to solve the problem.

[Vue.js] json data not showing in vuejs

when making a vue.js app. I put a .json file in static directory. when trying to read it in the default HelloWorld.vue.js file. But it’s not showing in the browser. Here is what it shows in the browser:

My json file looks like this:

{
“status”: “success”,
“message”: “Successfully reterived all registered applications”,
“Applications”: [
{
“ApplicationID”: “74382DOD”,
“ApplicationName”: “OIMInstance2”,
“ApplicationType”: “OIM”,
“APIToken”: “ZM8R4FRiZWWKbl235u06zbArCdOBPlEKhqHQO8Y9RJ2HgBPC+cZgbIli8fFuNZaey/2tJciJuILIWIn24WTjGA==”
},
{
“ApplicationID”: “943ODA6G”,
“ApplicationName”: “LDAPInstance2”,
“ApplicationType”: “LDAP”,
“APIToken”: “R9lDEW5dnN6TZg2sefEEzS6LWMNmFh4iLHMu47LmAsusHl0bZuh2rktSlXqSZRdHHEWq7sP4Xsdy6xNtDYE8xw==”
}
]
}

My code in HelloWorld.vue.js is:

<template>
<div>
<h1>APPLICATION REGISTRATION</h1>
<div v-for=”udata in userData”>
Id : { udata.ApplicationID }
</div>
</div>
</template>

<script>

import vue.js from ‘vue’
import axios from ‘axios’
import VueAxios from ‘vue-axios’

Vue.use(VueAxios, axios)

export default {
name: ‘HelloWorld’,

data () {
return {
userData: []
}
},

created: function() {
axios.get(‘../../static/mockdata.json’)
.then(response => {
this.userData = response.data
})
.catch(e => {
//this.errors.push(e)
})
}
}
</script>

Is there anything wrong with my code? How do I show the json data in the browser?

Solution :

You need to iterate through applications object.Hence in order to get applicationId you will need to set data accordingly by only adding applications data in the userData variable.

Do as below.

this.userData = response.data.Applications

[Vue.js] this.moveImage is not a function

i’m trying to use setInterval with my function moveImage which changes position of my image!
here is my code:

<template>
<div class=”randImg”>
<img v-bind:style=”{top: imgTop + ‘px’, left: imgLeft + ‘px’,height: imgHeight + ‘px’, width: imgWidth + ‘px’}”
class=”image” v-bind:src=”vue”>
</div>
</template>

<script>
const vue.js = require(“../assets/images/vue.png”);
export default {
name: “randImg”,
data() {
return {
vue,
imgTop: 0,
imgLeft: 0,
imgHeight: 64,
imgWidth: 64,
changeInterval: 1000
}
},
created() {
setInterval(this.moveImage(), this.changeInterval);
},
computed: {
moveImage() {
this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
}
}
}
</script>

as you can see when using vue.js and getting an error “this.moveImage is not a function”
help me please to solve that problem!

Solution :

That’s because moveImage is not a method is a computed property. As a computed property vue.js will generate a getter for it.

You need to move the definition to methods

methods: {
moveImage() {
this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
}
}

And in the call to setTimeout you want the function that its return value, so you need to call it like this

created() {
setInterval(this.moveImage, this.changeInterval);
}

[Vue.js] How to get object relation inside <option> loop in Vue?

Let’s go to the point of the question. there is a selection component, it looks like this:

<template>
<div class=”row”>
<div class=”col-md-6”>
<div class=”form-group”>
<label for=”category_id”>
Product Category
</label>

<select
name=”category_id”
id=”category_id”
:class=”form.errors.has(‘category_id’) ? ‘form-control is-invalid’ : ‘form-control’”
v-model=”form.sharedState.category_id”>

<option value=”” disabled hidden>Select Category</option>
<option
v-for=”category in categories”
:key=”category.id”
v-text=”category.name”
:value=”category.id”
@click=”$emit(‘category-selected’, category.sub_categories)”>
</option>

</select>

<small
class=”form-text text-danger”
v-if=”form.errors.has(‘category_id’)”
v-text=”form.errors.get(‘category_id’)”></small>

</div>
</div>
<div class=”col-md-6”>
<div
class=”form-group”
v-if=”revealSubCategory”
@category-selected=”show”>

<label for=”category_id”>
Sub Category
</label>

<select
name=”sub_category_id”
id=”sub_category_id”
:class=”form.errors.has(‘sub_category_id’) ? ‘form-control is-invalid’ : ‘form-control’”
v-model=”form.sharedState.sub_category_id”>

<option value=”” disabled hidden>Select Sub Category</option>

<option
v-for=”subcategory in subcategories”
:key=”subcategory.id”
v-text=”subcategory.name”
:value=”subcategory.id”>
</option>

</select>

<small
class=”form-text text-danger”
v-if=”form.errors.has(‘category_id’)”
v-text=”form.errors.get(‘category_id’)”></small>

</div>
</div>
</div>
</template>
<script>
import BaseCard from ‘./BaseCard.vue’;

export default {
components: {
BaseCard
},
data() {
return {
categories: [],
revealSubCategory: false,
subcategories: [],

form: new Form({
sharedState: product.data
})
}
},
mounted() {
this.getCategories();
},
methods: {
getCategories() {
axios.get(‘categories’)
.then(({data}) => this.categories = data);
},
show(subcategories) {
this.revealSubCategory = true;
this.subcategories = subcategories
}
}
}
</script>

And a select sub category input (it is there on the second column) which is will be displayed once the user has selected one of the categories options. Each category option has relation to sub categories taken from the API.

How can I get the sub categories and display the input? I already tried @change on the select tag but I can’t pass the sub category object because it is outside the loop. And @click event seems to be not working in an option tag.

Solution :

You can watch the v-model of the first select and change subcategory.

watch:{
“form.sharedState.category_id”: function (val) {
// update subcategories here
}

[Vue.js] Delete not working for Vue Route against API

when trying to setup a basic system where I can edit and delete values from a table. Been following a couple of guides and have hit a stumbling block.

<tbody>
<tr v-for=”(product,index) in products” @key=”index”>
<td>{index+1}</td>
<td v-html=”product.name”></td>
<td v-model=”product.units”>{product.units}</td>
<td v-model=”product.price”>{product.price}</td>
<td v-model=”product.price”>{product.description}</td>
<td><button class=”btn btn-primary” @click=”editingItem = product”>Edit</button></td>
<td><button class=”btn btn-primary” @click=”deleteProduct(product)”>Delete</button></td>

The second button then calls a deleteProduct method, and supplies the product for deletion.

deleteProduct(product) {
let id = product.id
let units = product.units
let price = product.price
let description = product.description
let image = product.image
axios.delete(“/api/products/“, {name, units, price, description, image})
.then(response => this.products.shift(product))

}

Axios makes a call on the ProductController’s destroy method.

public function destroy(Product $product)
{
$status = $product->delete();

return response()->json([
‘status’ => $status,
‘message’ => $status ? ‘Product Deleted!’ : ‘Error Deleting Product’
]);
}

And then lastly there is the API routes.

Route::group([‘middleware’ => ‘auth:api’], function(){
Route::get(‘/users’,‘UserController@index’);
Route::get(‘users/{user}’,‘UserController@show’);
Route::patch(‘users/{user}’,‘UserController@update’);
Route::get(‘users/{user}/orders’,‘UserController@showOrders’);
Route::patch(‘products/{product}/units/add’,‘ProductController@updateUnits’);
Route::patch(‘orders/{order}/deliver’,‘OrderController@deliverOrder’);
Route::resource(‘/orders’, ‘OrderController’);
Route::resource(‘/products’, ‘ProductController’)->except([‘index’,’show’]);
});

The last route is a resource from the ProductController, so it should give me all suitable methods. Using route:list also shows me that all of the routes have been setup correctly.

This issue comes when I actually try and delete a entry. All I get in return is a 405 error, which provides the following error.

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.

However I can clearly see DELETE method in route:list. Would anyone just be able to clarify if when missing something obvious here, or am I doing something fundamentally wrong?

Many thanks in advance!

Solution :

deleteProduct(product) {
let id = product.id
let units = product.units
let price = product.price
let description = product.description
let image = product.image
axios.delete(“/api/products/“ + product.id)
.then(response => this.products.shift(product))

}

You are missing product id in the ajax call. You should use /api/products/{id}

[Vue.js] Parsing nested JSON with Vuejs

there is a rather complex JSON file (output of elasticsearch engine) which I wish to parse using Vue. I managed to parse the JSON and access different values in it, but could not figure out how to parse an array found within the JSON - any suggestions?

Example JSON:

{
“hits”: [
{
“_index”: “people”,
“_type”: “lawyer”,
“_score”: 20.591383,
“_source”: {
“name”: “Miller J W”,
“address”: “Harvard Law School”,
“person_id”: 23615,
“keywords”: [
“Human”,
“Person”,
“Male”
]
},
“inner_hits”: {
“top_hits”: {
“hits”: {
“total”: 7,
“max_score”: 20.591383,
“hits”: [
{
“_index”: “contracts”,
“_type”: “contract”,
“_id”: “45386”,
“_score”: 20.591383,
“_source”: {
“pub_year”: 2013,
“keywords”: [
“Contract”,
“SPA contract”,
“legal doc”,
]
}
},
{
“_index”: “contracts”,
“_type”: “contract”,
“_id”: “45387”,
“_score”: 19.691383,
“_source”: {
“pub_year”: 2012,
“keywords”: [
“Contract”,
“CLA contract”,
“Pro bono”,
]
}
}
]
}
}
}
},
{
“pesron #2 etc…”
}
]

This is how I parse the JSON using vue:

<ol>
<li v-for=”person in people”>
{ person._source.name }
{ person._source.address }
{ person._source.address_person_id }
{ person.inner_hits.top_hits.hits.total }

</li>

But how do I parse the “hits” under “top_hits”??

Thanks!!

Solution :

Start with computed property to simplify input data.

computed: {
people() {
let people = []
this.json.hits.forEach((item) => {
let hits = item.inner_hits.top_hits.hits
people.push({
_source: item._source,
hits: hits,
})
})
return people
}
}

the template should looks like:

<ul>
<li v-for=”person in people”>
{ person._source.name }<br>
{ person._source.address }<br>
{ person._source.address_person_id }<br>
{ person.hits.total }<br>
<ul>
<li v-for=”hit in person.hits.hits”>
{ hit._source.pub_year }
[…]
</li>
</ul>
</li>
</ul>

[Vue.js] How can I test vuex action which with jest which has an api call inside it?

ASYNC ACTION VUEX : This is async action which will be called from the
component, it consists of an function fetchGaragesData that will make
an api call to fetch data from server.

[ACTION_TYPES.FETCH_CASHLESS_GARAGES]: async (
{ dispatch, commit, state, rootState },
payload
) => {
commit(MUTATION_TYPES.SET_MISC_KEYS, {
fetchingCashlessGaragesInitiated: true,
})
let { insurerSlug, makeId, rtoCode } = payload
const url = ApiUrls.getCashlessGarages + `${insurerSlug}/${makeId}`
const response = await fetchGaragesData(url, rtoCode)
dispatch(ACTION_TYPES.MODIFY_RTO_WISE_GARAGES_DATA, response)
},

IMPLEMENTATION OF fetchGaragesData: this function internally calls
axios get:

export const fetchGaragesData = (url: string, rtoCode: string) => {
return get(url, {
rto_code: rtoCode,
all_states_data: true,
})
}

How can I test action ACTION_TYPES.FETCH_CASHLESS_GARAGES ???

Solution :

You might be having API mock response. So, in the spec file you need to add the mock response for that particular API call.

Include the file in spec file which has the actual backend API call.
For example:

import someName from ‘path of file’

jest.mock(‘someName’, () => ({
fetchGaragesData: jest.fn((url, rtoCode) =>
success({ body:
Here comes the response body
})
)

url and rtoCode should be the name of the variables used in the API call file.

[Vue.js] using jquery in vue js in Laravel 5.7

when a bit confused about steps of jquery installation and usage. Jquery is already in package.json

“devDependencies”: {
“jquery”: “^3.2”,
“laravel-mix”: “^4.0.7”,

And my laravel-mix looks like below.

mix.js(‘resources/js/app.js’, ‘public/js’)
.sass(‘resources/sass/app.scss’, ‘public/css’);

And App.js

require(‘./bootstrap’);
require(‘./jquery’);

window.vue.js = require(‘vue’);

Vue.component(‘index-content’, require(‘./components/Index.vue’).default)

const app = new Vue({
el: ‘#app’,
// router
});

Index.vue

<script>

import JQuery from ‘jquery’;
let $ = JQuery

$(“#btn”).click(function(){
$(“#hello”).toggle();
});

export default {

data() {


}
}
</script>

when not sure, am I missing something here or not. Additionally about the Jquery usage in vue.js template: in my Index.vue.js do I just need to open another script tag after <template> and write jquery code there? or in vue.js writing is different? Because my jquery code is not working in Index.vue

Solution :

You need to import it in app.js file as

window.$ = require(‘jquery’)
window.JQuery = require(‘jquery’)

[Vue.js] Vue loses prototypes and imported files when creating new component

When extending a vue.js component to a modal, a new vue.js instance is generated. This leads to losing all pre-imported helpers/ Vuex-stores etc.

Is there a way how to copy all data to the new extended vue.js component?

To make it clear, have a look at this jsfiddle.

It confronts you with an alert. When you click on the button, the modal is opened. But if you look at my code, another alert should be fired. But $hi() is not available in the other vue.js instance.

I create a component like this:

const createComponent = (props) => {
const wrapper = document.createElement(‘div’);

const Component = Vue.extend(MyComponent);

return new Component({
propsData: {
props,
},
}).$mount(wrapper);
};

I’m using SweetAlert as a modal.

So I add this like:

swal({
content: createComponent(props).$el,
})

Solution :

If you move the line

Vue.prototype.$hi = () => alert(‘hi’);

above

let component = new TestComponent().$mount(wrapper)

it will work. the first component references $hi() before it’s defined.

[Vue.js] How can I inject a js when a div become visible?

I’d need to keep initial page load as fast as possible so I’m trying to avoid loading gmaps, paypal, stripe or similar js when the page loads as I need them only after the user clicked a button and a div gets visible.

there is a

<div class=”container” v-if=”step != ‘0’” v-cloak>

</div>

I tried to put “<script src=”https://js.stripe.com/v3/"></script>" within the div but this doesn’t work, the js is loaded during the initial page load.

How can I inject js in Conditional Rendering?

Solution :

Watch the step and append script to DOM:

data() {
return {
//…
jsInjected: false,
//…
}
},
watch: {
step(val, oldVal) {
if(! this.isInjected && val != ‘0’) {
let s = document.createElement(“script”);
s.type = “text/javascript”;
s.src = “https://js.stripe.com/v3/";
document.head.appendChild(script);

this.jsInjected = true; // prevent to append more than once.
}
}
}