# [Vue.js] Add parent class name values to each v-for child element

Im trying to figure out a way to split values from a parent classname and add each separate value to each child inside the parent (the number of child elements is variable).

There might be class names with one value or multiple values. The number of child elements matches the values in the block-classname e.g block-25-50-25 will have 3 child elements.

there is an example in JS but Im not sure how to use it in Vue: https://jsfiddle.net/8y9k6at3/

Example

<div class=”block-33-33-33-33”>
<div class=”card”>1</div>
<div class=”card”>2</div>
<div class=”card”>3</div>
<div class=”card”>4</div>
</div>

var pClass = document.querySelector(‘div[class^=block]‘).classList.value.split(‘-‘);
pClass.shift(); // remove the first item

console.log(pClass.shift())

document.querySelectorAll(‘div.card’).forEach(function(el, i){
});

Page.vue

<div
:class=”splitClass” // This returns a classname which could be block-25-50-25 or block-33-33-33 etc
class=”wrapper__content”
\>
<div
v-for=”(contentItem, index) in content.content”
:key=”contentItem[‘id’]“
class=”card” // Block value here.
\>
</div>
</div>

Computed

splitClass() {
const { split } = this.content;
if (split) {
\>
</div>
</div>

# [Vue.js] Inline an SVG file in Vue with v-bind feature on source

Final Goal : Include SVG icons from files with the possibility to use CSS on it (mainly on the fill parameter). This seems to mean having a way to inline the SVG file in the vue.js template.

there is found plenty of solutions involving webpack loaders (vue-svg-inline-loader, vue-svg-loader, and 2 or 3 others), but I also want to be able to choose dynamically which file I load by using a v-bind directive on the source parameter. Something like :

<img :src=”path/to/${file}.svg“ /> or <custom-component :src=”path/to/${file}.svg“ />

And none of the webpack loaders seems to allow that. I found no vue.js plug-in with this feature.

My porject is a quasar-framework project, if this can help.

### Solution :

You can do like that:

<template v-html=”svgFile”></template>

computed:{
svgFile(){
require(path/to/${this.file}.svg) } } But you also need config the webpack to out put the svg as raw html. Using some plugin like svg-inline-loader or whatever you want. See more { test: /\.svg$/, loader: ‘svg-inline-loader’ }

# [Vue.js] Vue-Bootstrap how to trigger sorting of one b-table to trigger sorting of the another b-table?

I’m using VueBoostrap <b-table> components, in a combination with sorting routine applied. In my project there is some more complex sorting routine, but for this dummy example, I will use the default one.

When a sorting is applied for a b-table, the table is simply sorted based on the clicked field in the table header. But what I need to achieve is to split the table header from the table content (since to place the content in a scrollable div later, while the header to remain static at the top - as user will be scrolling).

The complete code is given on this link (check componets/TableTest.vue), where there is three <b-table> components. First one is just a dummy example, and the next two are identical as the first one, but for one of them the header is hidden and for the other the body is hidden.

What to achieve is:

### Solution :

If you take a close look at the docs (https://bootstrap-vue.js.org/docs/components/table) you can see that there are certain events emitted by the <b-table> component.
One of them is sort-changed. So if you listen for that on the header only component and then set a sortBy property that you pass into the body only component you’re all set.

<b-table … @sort-changed=”sortChanged”>

// body only
<b-table :sort-by=”sortBy” …>

sortChanged(e) {
this.sortBy = e.sortBy
}

Full example here: https://codesandbox.io/s/y30x78oz81

# [Vue.js] Vue app blank page in IE 11 or lower even with polyfills

there is a vue.js app running in Firefox, Edge, and Chrome, however, in IE 11 (or lower), I see a blank page. And in the console of IE is see something like SCRIPT1002: Syntax error app.js and SCRIPT5022: SecurityError sockjs.js.

The syntax error goes to a line that contains: eval(“__webpack_require__.r(__webpack….Verry long string).

The security error goes to a block that contains:

var Driver = global.WebSocket || global.MozWebSocket;
if (Driver) {
module.exports = function WebSocketBrowserDriver(url) {
return new Driver(url); // Where this line is marked
};
} else {
module.exports = undefined;
}

After some research, I found out that it might have something to do with missing polyfills. So I added import “@babel/polyfill”; to main.ts and presets: [[“@vue/app”, { useBuiltIns: “entry” }]] to babel.config.js. But the same errors appear in IE. I tried some other methods described in https://cli.vuejs.org/guide/browser-compatibility.html. But none had success for me.

At this point, I’m absolutely clueless because of similar problems on the internet all point at missing polyfills.

Some extra info about the app:

Was created using the vue.js cli 3
Uses typescript.
Uses some new js features like Object.entries

Update:

Looking a bit more at the error there is found that IE11 has problems loading the vuex-persist module in my app. I’m continuing my search.

### Solution :

So the issue was with a dependency I was using. vuex-persist was causing the issue. The fix was to add the following in vue.config.js:

module.exports = {

/* … other config … */

transpileDependencies: [‘vuex-persist’]

}

# [Vue.js] How to get the value from an input in my codebehind while using @keyup

there is an input box that the user types a phone number and it formats it for them.

<label>Primary Phone Number</label><input type=”text” class=”form-control” id=”primaryPhone” placeholder=”Primary Phone Number” v-model=”primaryPhone” maxlength=”12” @keyup=”formatPhone” />

there is my formatting for the phone number below using Vue.js.

formatPhone: function (event) {
if ([‘Arrow’, ‘Backspace’, ‘Shift’].includes(event.key)) {
this.preventNextIteration = true;
return;
}
if (this.preventNextIteration) {
this.preventNextIteration = false;
return;
}

if (this.step === 4 && event.target.id === ‘primaryPhone’) {
var a = this.primaryPhone.replace(/-/g, ‘’).match(/(\d{1,10})/g)[0];

this.primaryPhone = a.replace(/(\d{1,3})(\d{1,3})(\d{1,4})/g, ‘$1-$2-$3’); } } My submit button then runs my btnSubmit function on the code behind like so <button id=”submit” v-show=”agreement === true” class=”btn” runat=”server” onserverclick=”btnSubmit” style=”float:right”>Submit</button> I need to get the value of the input box in my C# code behind. I know that I cannot use runat=”server” because this will throw the server tag is not well formed with the @keyup. So I tried to get my value in C# using Request[“primaryPhone”] or Request.Form[“primaryPhone”] and neither worked. Both said that the object was undefined. How can I get my value in the code behind while using my validation? I thought about using a hidden field running at the server and just setting that value to the value of my input as a last resort. I feel like there might be a simpler way though. ### Solution : You aren’t setting a name for the input. Try this <input type=”text” class=”form-control” id=”primaryPhone” name=”primaryPhone” placeholder=”Primary Phone Number” v-model=”primaryPhone” maxlength=”12” @keyup=”formatPhone” /> Why does the name param matters ? When the browser makes an HTTP request because of a form submit it looks at all input descendants that are not disabled. after that, depending on the type of input (text, radio, checkbox) it gets their value. when making the request it needs to fill in a list of key, value pairs (this actually depends on the enc type). The key for each input is the value of the name attribute and not the id. # [Vue.js] Split a parent class name and add to each child element I’m trying to figure out a way to split values from a parent classname and add each separate value to each child inside the parent (the number of child elements is variable). There might be class names with one value or multiple values. <div class=”block-33-33-33-33”> <div class=”card block__col–33”></div> <div class=”card block__col–33”></div> <div class=”card block__col–33”></div> <div class=”card block__col–33”></div> </div> or <div class=”block-50-50”> <div class=”card block__col–50”></div> <div class=”card block__col–50”></div> </div> or <div class=”block-100”> <div class=”card block__col–100”></div> </div> What would the best way to handle this? Thanks. ### Solution : You can try using querySelector() and querySelectorAll() like the following way: var pClass = document.querySelector(‘div[class^=block]‘).classList.value.split(‘-‘); pClass.shift(); // remove the first item document.querySelectorAll(‘div.card’).forEach(function(el, i){ el.classList.add(‘block__col–’+ pClass[i]); }); .block__col–33{ font-size: 20px; color: red; } <div class=”block-33-33-33-33”> <div class=”card”>1</div> <div class=”card”>2</div> <div class=”card”>3</div> <div class=”card”>4</div> </div> ### Solution 2: let parentDiv =$(“body > div”)
let parentClassArr = parentDiv.attr(‘class’).split(‘-‘)
for (let i = 1; i < parentClassArr.length; i++) {
parentDiv.children().eq(i - 1).addClass(parentClassArr[0] + ‘__col–’ + parentClassArr[i])
console.log(parentDiv.children().eq(i - 1).attr(‘class’))
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
<div class=”block-33-33-33-33”>
<div class=”card”></div>
<div class=”card”></div>
<div class=”card”></div>
<div class=”card”></div>
</div>
</body>

### Solution 3:

const blocks = document.querySelectorAll(“[class^=block-]“);
blocks.forEach(splitParentClassNameToChildren);

function splitParentClassNameToChildren(parent) {
const { className } = parent;
const splitValues = className.match(/(\d\d)/g);
splitValues.forEach((value, i) => {
parent.children[i].classList.add(block__col–${value}); }) } In action => https://jsfiddle.net/moorthyrweb/z3jLqwn4/14/ # [Vue.js] How to prevent click event in link or button using Vue directive Hi I’m playing around with vue.js directives and I’m trying to prevent click event if the element is <a> or <button> tag. So my question is, is this possible to do using vue.js directive? Html <a @click.stop.prevent=”displayModal()” v-noclick=”test”> I’m a link </a> vue.js directive Vue.directive(‘noclick’, { bind( elem, binding, vnode ) { let user = {‘name’: ‘John Doe’} if( user ) { let hasAccess = false if( !hasAccess ) { if( elem.tagName === ‘A’ ) { elem.addEventListener( ‘click’, ( event ) => { //this should prevent the element on click event //but not working event.stopPropagation() event.preventDefault() event.stopImmediatePropagation() return false }) return true } } } } } ### Solution : vue.js registers the @click event first before v-noclick where you add a second click event listener on that element. When the <a> is clicked, the displayModal() function will be executed first, then the listener in the v-noclick directive will be executed. If the listeners were registered in the opposite order, then it would probably work. That aside though, it doesn’t look like what you are trying to do should be done inside a custom directive. Instead you can do the same logic in the click handler itself: <a @click=”onClick”>Foo</a> onClick() { if (whatever) { this.displayModal() } } # [Vue.js] Static files are missing in VueJS application My first VueJS application structure is as simple as: - src/ - App.vue - main.js - static/ - data.json - assets/ - data.json - .gitignore - babel.config.js - package.json - README.md babel.config.js looks like this: module.exports = { presets: [ ‘@vue/app’ ] } And package.json is just that simple: { “name”: “test-app”, “version”: “0.1.0”, “private”: true, “scripts”: { “serve”: “vue-cli-service serve”, “build”: “vue-cli-service build”, “lint”: “vue-cli-service lint” }, “dependencies”: { “axios”: “^0.18.0”, “vue”: “^2.6.9”, “vuetify”: “^1.5.6” }, “devDependencies”: { “@vue/cli-plugin-babel”: “^3.5.1”, “@vue/cli-plugin-eslint”: “^3.5.1”, “@vue/cli-service”: “^3.5.1”, “babel-eslint”: “^10.0.1”, “eslint”: “^5.15.2”, “eslint-plugin-vue”: “^5.2.2”, “stylus”: “^0.54.5”, “stylus-loader”: “^3.0.2”, “vue-template-compiler”: “^2.6.9” }, “eslintConfig”: { “root”: true, “env”: { “node”: true }, “extends”: [ “plugin:vue/essential”, “eslint:recommended” ], “rules”: {}, “parserOptions”: { “parser”: “babel-eslint” } }, “postcss”: { “plugins”: { “autoprefixer”: {} } }, “browserslist”: [ “> 1%”, “last 2 versions”, “not ie <= 8” ] } Finally, I build my application with this command:$ npm run build

As a result I get dist folder. However, as I can see there is no assets or static folder inside it. So, when I go to http://localhost/static/data.json or http://localhost/assets/data.json I get this error message:

How can I fix it?

### Solution :

may it works for you add this to the web-pack.production.js

new CopyWebpackPlugin([
{
from: path.resolve(__dirname, ‘../static’),
to: config.assetsSubDirectory,
ignore: [‘.*‘],
},
]),

# [Vue.js] Why is my vuetify dialog hidden behind this evil overlay?

there is a vuetiful component which should just display a dialog. Unfortunately, an evil overlay has taken over the domverse. How do I overcome the forces of semi-transparent darkness?

Vue.component(‘step-form’, {
data: function() {
return {
dialog: false
}
},
methods: {
showDialog() {
this.dialog=!this.dialog;
}
},
template: 
<v-dialog v-model=”dialog” persistent max-width=”600px”>
Help, I’m hidden behind this evil “overlay”!
</v-dialog>

});

https://codepen.io/anon/pen/jJpWGx

### Solution :

use hide-overlay

change to below code

<v-dialog hide-overlay
v-model=”dialog” persistent max-width=”600px”>
Help, I’m hidden behind this evil “overlay”!
</v-dialog>

Documentation : https://vuetifyjs.com/en/components/dialogs

### Solution 2:

It’s not.

You simply don’t have background color inside v-dialog. You can put v-card inside for example.
You just used persistent property which makes you unable to close it on-overlay-click, and have no other means to close it.
So dialog has z-index: 202, and overlay has 201 apparently, so dialog is above overlay,
but box-shadow makes it look like like it’s floating behind it or something, but it’s because it’s transparent, and you just need to set background-color.

# [Vue.js] Internet explorer cancels ajax requests

when making a request to the server through Ajax -Jquery, this request returns more than 2000 records (about 16,000 records)

In google chrome executed the call although it took about 40 seconds but in internet explorer 11 the execution is canceled and no error is displayed in the console, it simply never makes the call.

To reduce execution times when trying to call 1500 records, in google chrome it works perfectly but in internet explorer only makes the first call:

mostrar: function() {