link3014 link3015 link3016 link3017 link3018 link3019 link3020 link3021 link3022 link3023 link3024 link3025 link3026 link3027 link3028 link3029 link3030 link3031 link3032 link3033 link3034 link3035 link3036 link3037 link3038 link3039 link3040 link3041 link3042 link3043 link3044 link3045 link3046 link3047 link3048 link3049 link3050 link3051 link3052 link3053 link3054 link3055 link3056 link3057 link3058 link3059 link3060 link3061 link3062 link3063 link3064 link3065 link3066 link3067 link3068 link3069 link3070 link3071 link3072 link3073 link3074 link3075 link3076 link3077 link3078 link3079 link3080 link3081 link3082 link3083 link3084 link3085 link3086 link3087 link3088 link3089 link3090 link3091 link3092 link3093 link3094 link3095 link3096 link3097 link3098 link3099 link3100 link3101 link3102 link3103 link3104 link3105 link3106 link3107 link3108 link3109 link3110 link3111 link3112 link3113 link3114 link3115 link3116 link3117 link3118 link3119 link3120 link3121 link3122 link3123 link3124 link3125 link3126 link3127 link3128 link3129 link3130 link3131 link3132 link3133 link3134 link3135 link3136 link3137 link3138 link3139 link3140 link3141 link3142 link3143 link3144 link3145 link3146 link3147 link3148 link3149 link3150

[Vue.js] How to declare javascript class instance in vue?

I need to get access to the data stored in canvas.js in my vue.js. For this there is to create the instance of canvas in my vue. But there is some issues with this.

I found the similar problem as mine but the answer doesnt set up for me, I also tried require.
I also find some solution with ES6, but I dont use ES6, but I also tried it, not working.

This what I type in Vue.js

import Canvas from ‘./canvas.js’;

Canvas.js

export default class Canvas{
contructor(){
this.devices = [“5”, “15”];
}

I wonder why does first solution didnt help me, bcz my problem is very similar. If I comment with “//“ the import in Vue.js everything working fine. Maybe there are another solution without using import, but I need to have access to the data stored in Canvas.

P.s pls dont recommend to use components bcs im planning to store another class instance in devices of Canvas, and there would be too much of useless components(imho bcs im noob in vue)

UPD: My issue that the code doest not compile after “import”, and there is this .

but If i put “import” to comment “//“ the situation is like

UPD2: The full Vue.js file

//import Canvas from ‘./canvas.js’;
var app1 = new Vue({
el: ‘#vue1’,
data: {
arr2: [8, 7, 6, 5]
},
methods: {
addArr1: function(num){
this.arr2.push(num)
}
}
});

canvas.js

export default class Canvas{
contructor(){
this.devices = [“5”, “15”];
}

my index.html

<div id=”vue1”>
<ul v-for=”ar in arr2”>
<li>{ ar }</li>
</ul>
<button v-on:click=”addArr1(15)”>CLICK</button>
</div>

Solution :

Using ES Modules in the browser requires you to use a different mechanism to load the scripts. Essentially, you should have an “entry point” that you load and that can import varying modules you need to run. This entry point should be defined using a <script type=”module” src=”whatever.js”>, note the type=”module. You can read about it here: MDN <script>.

If you don’t use type=”module”, you can’t use import unless you run a transpiler like webpack. vue.js has a bootstrapping application that helps you set up a vue.js project that leverages webpack here: vue-cli.

the application will effectively look something like this:

Canvas.js

export default class Canvas {
contructor() {
this.devices = [“5”, “15”];
}
}

my-cool-script.js

import vue.js from “https://unpkg.com/vuex@3.1.0/dist/vuex.esm.js";
import Canvas from “./Canvas.js”;

var app1 = new Vue({
el: ‘#vue1’,
data: {
arr2: [8, 7, 6, 5]
},
methods: {
addArr1: function(num) {
this.arr2.push(num)
}
}
});

index.html

<script src=”my-cool-script.js” type=”module”></script>
<div id=”app”></div>

If you do not use type=”module”, you cannot use import without transpiling. the project would basically look like this:

Canvas.js

class Canvas {
contructor() {
this.devices = [“5”, “15”];
}
}

my-cool-script.js

var app1 = new Vue({
el: ‘#vue1’,
data: {
arr2: [8, 7, 6, 5]
},
methods: {
addArr1: function(num) {
this.arr2.push(num)
}
}
});

index.html

<script src=”https://cdn.jsdelivr.net/npm/vue"></script>
<script src=”Canvas.js”></script>
<script src=”my-cool-script.js”></script>
<div id=”app”></div>

[Vue.js] vuejs router in loop

there is below beforeEach code in my vue.js js. I need to only check for loggedIn and not authRequired. If I remove the authRequired from the if condition, this function looks. Is there any other way I can just check localstorage value and not check authRequired.

router.beforeEach((to, from, next) => {
const publicPages = [‘/login’, ‘/register’];
const authRequired = !publicPages.includes(to.path);
const loggedIn = localStorage.getItem(‘user’);

if (authRequired && !loggedIn) {
return next(‘/login’);
}

next();
})

there is tried before code. Which gets stuck in continuous loop.

router.beforeEach((to, from, next) => {
const publicPages = [‘/login’, ‘/register’];
const loggedIn = localStorage.getItem(‘user’);

if (!loggedIn) {
return next(‘/login’);
}

next();
})

Solution :

I can’t see any way If you want to keep using the global guards (the router.beforeEach).
If you are willing to stop using the global route guards you can use the beforeEnter and apply it to every route manually. In this solution will be able to use the second function on every route except the ‘login’ route.

const authGuard = (to,from,next) => {
const loggedIn = localStorage.getItem(‘user’);

if (!loggedIn) {
return next(‘/login’);
}

next();
}

const routes = [
{
path: ‘/login’,
component: Login
},
{
path: ‘/someProtectedRoute’,
component: Bar,
beforeEnter: authGuard
},
{
path: ‘/anotherProtcted’,
component: Bar,
beforeEnter: authGuard
}
]

[Vue.js] VueJS async detect language with Yandex Translate API

I’m experimenting with Yandex Translate API using VueJS to detect the language of the entered text asynchronously.

Everything works right. But there is a problem; log returns for each letter I write.

For example, when I write ‘hello’: api predicts the language of each of the words ‘h’, ‘he’, ‘hel’, ‘hell’, ‘hello’ and turns 5 log. What is that the API returns 1 log for the word ‘hello’ asynchronously after the timeout. It checks it for every letter. How can I fix it?

Html part of TranslateForm.vue

<template>
<textarea v-model=”translateText” cols=”30” rows=”5” class=”form-control” placeholder=”Translate something.”></textarea>
</template>

Script part of TranslateForm.vue

import axios from ‘axios’
export default {
name: ‘TranslateForm’,
data () {
return {
translateText: ‘’,
apiKey: ‘********‘,
detectLangApiUrl: ‘***********‘
}
},
watch: {
translateText (value) {
if (value) {
axios.post(this.detectLangApiUrl + ‘?key=’ + this.apiKey + ‘&text=’ + value)
.then(response => {
console.log(response)
}).catch(e => console.log(e))
}
}
}
}

Solution :

The problem is that you are calling the API every time translateText is updated (after each key press). If you don’t want to simply have a button, one way to do that would be to listen to the blur event (when the user focuses out of the textarea) and call the method then:

<template>
<textarea v-model=”translateText” @blur=”translate” cols=”30” rows=”5” class=”form-control” placeholder=”Translate something.”></textarea>
</template>

<script>
import axios from ‘axios’
export default {
name: ‘TranslateForm’,
data () {
return {
translateText: ‘’,
apiKey: ‘********‘,
detectLangApiUrl: ‘***********‘
}
},
methods: {
translate () {
if (this.translateText) {
axios.post(this.detectLangApiUrl + ‘?key=’ + this.apiKey + ‘&text=’ + this.translateText)
.then(response => {
console.log(response)
}).catch(e => console.log(e))
}
}
}
}
</script>

You could also limit the number of times the method is called, using a debounce function. For example, to call translate only once every second:

<script>
import axios from ‘axios’
import { debounce } from ‘lodash’

export default {
name: ‘TranslateForm’,
data () {
return {
translateText: ‘’,
apiKey: ‘********‘,
detectLangApiUrl: ‘***********‘,
debouncedTranslate: debounce(() => {
axios.post(this.detectLangApiUrl + ‘?key=’ + this.apiKey + ‘&text=’ + this.translateText)
.then(response => {
console.log(response)
}).catch(e => console.log(e))
}, 1000)
}
},
watch: {
translateText (value) {
if (value) {
this.debouncedTranslate()
}
}
}
}
</script>

[Vue.js] How can i use an multidimensional array for the v-model in Vue?

to generate an attribute variation for an online shop based on attribute values checked by user.

The problem is that i don’t know how access the values of attributes from the v-model and what type of data must be the v-model?

I’m stuck here.Below is my code.

Thank you!

<div v-for=”(attribute, index) in attributes”>
<p>{ attribute.name }</p>
<div v-for=”(attributevalue,indexval) in attribute.attribute_values”>
<input v-model=”attributes[index][indexval]“ :value=”attributevalue.id”>
<label>{ attributevalue.name }</label>
</div>
</div>
<p>Generate</p>

export default {
props:{
attributes:{
type:Array
}
}
}

Solution :

If you want to bind ‘id’ to input then, this is what you should do -

<input type=”text” v-model=”attributevalue.id” >

This attributes[index][indexval] won’t be needed as you have a nested for loop which does exactly the same. Hence, you can use directly attributevalue to access its properties in v-model.

A note about v-model:

It is a two way binding mechanism in vue.js and it will accept any type of value you want to pass to the underlying component as long as the component supports the type. In this case, input with type text accepts string/numeric values.

v-model internally uses different properties and emits different events for different input elements:

text and textarea elements use value property and input event;
checkboxes and radiobuttons use checked property and change event;
select fields use value as a prop and change as an event.

[Vue.js] Vue - Clear true false toggles from out side a loop

when relatively new to Vus.js and vanilla js, Im looking for some help. there is a loop where filters are toggled between false and true depending on the criteria. there is a button outside of all the vue.js loops that I would like to use to clear all the toggles - set all the data back to false.

when using axios and a json file for my data. Theere are three filess when working with filters.json, filters.js and the html

Thanks in advance for you help
json

[{
“name”: “Category”,
“filterVisible”: false,
“buttonActive”: false,
“values”: [{
“name”: “Single Cask”,
“selected”: false
},
{
“name”: “Regional Malt”,
“selected”: false
},
{
“name”: “New releases”,
“selected”: false
}
]
},

{
“name”: “Region”,
“filterVisible”: false,
“buttonActive”: false,
“values”: [{
“name”: “Highland”,
“selected”: false
},
{
“name”: “Speyside”,
“selected”: false
},
{
“name”: “Islay”,
“selected”: false
}
]
},

{
“name”: “Brand”,
“filterVisible”: false,
“buttonActive”: false,
“values”: [{
“name”: “Regional Malts”,
“selected”: false
},
{
“name”: “Single Casks”,
“selected”: false
},
{
“name”: “The Big Yin”,
“selected”: false
},
{
“name”: “The Wee Yin”,
“selected”: false
}
]
},

{
“name”: “Price”,
“filterVisible”: false,
“buttonActive”: false,
“values”: [{
“name”: “1-50”,
“selected”: false
},
{
“name”: “51-100”,
“selected”: false
}
]
}
]

fliters.js

var vm = new Vue({
el: ‘#app’,
data: {

shopFilters: []
},

created() {

axios
.get(`shopFilters.json`)
.then(response => {
// JSON responses are automatically parsed.
this.shopFilters = response.data;
})
},
computed: {

}, // end computed

methods: {
// my attempt at clearing filter
clearAll: function(filter) {
shopFilters.filterVisible = false
}
}

});

html

<div class=”shop__filter”>
<div class=”shop__filter-header”>
<h6 class=”shop__filter-heading”><img src=”img/filter-symbol.png” />Filter</h6>
<p class=”shop__filter-showing”>showing 1-8 of 120</p>

**this is the bit to call the Function on**

<button @click=”clearAll()” class=”btn btn-white btn-mobile”>clear filters</button>

</div>
<form>

<dl class=”shop__filter-list”>

<template v-for=”filter in shopFilters”>

<dt class=”shop__filter-dt”>
<button class=”shop__btn-type”
v-on:click=”filter.buttonActive = !filter.buttonActive”
:class=”{‘active’ : filter.buttonActive}”
@click=”toggle(filter)”
@click.self.prevent>
{ filter.name }
</button>
</dt>

<dd class=”shop__filter-dd”
v-show=”filter.filterVisible || option.selected”
:id=”filter.name”
v-for=”option in filter.values”>

<button class=”shop__btn-filter”
@click.self.prevent
v-on:click=”option.selected = !option.selected”
:class=”{‘active’ : option.selected}”>
{ option.name }
</button>
</dd>

</template>

</dl>
</form>
</div>

Solution :

I got a fix for this

clearAll: function() {
for (var i = 0; i < this.shopFilters.length; i++) {
var filter = this.shopFilters[i];
filter.buttonActive = false;
filter.filterVisible = false;
for (var j = 0; j < filter.values.length; j++) {
var option = filter.values[j];
option.selected = false;
}
}
}, // end clearAll

[Vue.js] How can I prevent modal to hide when submitting form?

I’m working with my server-side validation with inspiring from laravel. I’m struggling putting validation in my modal and also with type=”submit” button. When I click the save button with empty inputs the modal is closing and when I open the modal again the error is already there. to avoid modal to hide when submitting the form. How can I stop modal to close if the inputs are empty? I’m using type=”submit” button?

addUnitCategory : function() {
axios({
method : “POST”,
url : this.urlRoot + “unit_category/add_unit_category.php”,
data : {
description : this.unit_category_description,
unit : this.unit_category_unit
}
}).then(function (response){
vm.retrieveUnitCategory();
swal(“Congrats!”, “ New unit category added!”, “success”);
vm.clearData();
}).catch(error => {
console.info(error.config);
});
},
validationCategoryUnit : function() {
if (this.unit_category_description || this.unit_category_unit) {
$(‘#myModal’).modal(‘hide’);
vm.addUnitCategory();
return true;
}
if (!this.unit_category_description || !this.unit_category_unit) {
return false;
}
},

<–Form–>
<form method=”post” @submit=”validationCategoryUnit()”>
<–Button–>
<div class=”modal-footer”>
<button type=”submit” @click=”validationCategoryUnit()”>Save</button>
</div>

<–Validation–>

if($_SERVER[‘REQUEST_METHOD’] == “POST”) {
$validation = new Validation();
$data = [
“unit_category_description” => $_POST[‘unit_category_description’] ? ‘unit_category_description’ : ‘’,
“unit_category_unit” => $_POST[‘unit_category_unit’] ? ‘unit_category_unit’ : ‘’,
];
$validation->validate($data, [
“unit_category_description” => “required|maxlen:45”,
“unit_category_unit” => “required|minlen:5|maxlen:20”
]);

$errors = $validation->getErrors();
} else {
$data = [
“unit_category_description” => “”,
“unit_category_unit” => “”
];
$errors = [
“unit_category_description” => “”,
“unit_category_unit” => “”
];
}
if (isset($_POST[‘submit’])) {
if($data) {
echo $data;
}

Solution :

I you want you can submit the form from the js code instead of using submit button.
In Jquery it will look like this:

$(“#MyForm”).submit()

Using that you can control when the form is submitted according to the modal.
Hope it helped.

[Vue.js] How to import whole SCSS folder in Vue Nuxt project?

At my company we are not writing css in vue.js files, we prefer to do it the old way with SCSS.

Problem is, we end up with a need of writing new import in styles.scss any time we create new component, and it really bugs me in bigger projects.

Not so long ago, when there is been developing in React, I imported module called node-sass-glob-importer in webpack.config file, tweaked a bit (you can check here) and it worked - I could have imported folder like this: @import “components/**“;

In Nuxt, I only have nuxt.config.js file and when lost a bit. I know how to extend some simple stuff there, but this seems to be more complicated.

Any help of importing node-sass-glob-importer or doing the same thing in some other way?

Solution :

how about using https://github.com/nuxt-community/style-resources-module and than:

export default {
modules: [‘@nuxtjs/style-resources’],
styleResources: {
scss: [
‘./assets/yourFolder/*.scss’
]
}
}

[Vue.js] Vuejs active router link does not work, tried multipled ways

I cannot make the active button (router-link tag) to light up.

Here is my code:

<div class=”bottom-buttons”>
<span v-for=”button in buttons” class=”button” :class=”{ ‘is-active’: $route.path === button.path}”>
<router-link :to=”button.path”>
<i :class=”button.iclass”></i>
<p class=”button-label”>{button.label} </p>
</router-link>
</span>
</div>

When I print out $route.path it returns the right path, and button.path is the data there is in the data object, and it works. So the condition should be right. But the ‘is-active’ class is not activated. (This thread: VueJS exact-active-class)

If I hard-code the ‘is-active’ class, it works.

When I use a:hover, a:visited, a:link it works, but a:active does not work :D. there is tried a:router-link-active but it does not work. (This thread: How to VueJS router-link active style)

there is tried to add linkActiveClass: ‘is-active’ in the /router/index.js file as suggested. It does not work. (This thread: Bulma navbar and VueJS router active link)

Anybody knows why? Or have more suggestions? Thank you in advance!

Solution :

It seems to be that the problem is in the class condition. Maybe try to use == instead of === in the :class?

I would have add a comment instead of an answear if i had enough reputation :)

[Vue.js] All requests return one by one, not concurrently

could you please help me with my code. I need run requests concurrently but get requests one by one. Below code example (use VueJS method/function)

async manageData() {
// array of chart’s properties
const charts = await axios.post(‘/report/chart_data’, {id: this.id);
// concurrent requests with variable ‘charts’
const result = await Promise.all(
charts.map((chart, key) => axios.post(‘/report/data_range’, {id: key}))
);
}

Solution :

const charts = await axios.post(‘/report/chart_data’, {id: this.id);

Will make a single request and wait until it is completed before continuing. This is necessary, as you then use the charts response to form the subsequent requests.

charts.map((chart, key) => axios.post(‘/report/data_range’, {id: key}))

Will make charts.length number of requests in parallel. This is desirable per the description and because it appears the requests are independent.

the screenshot supports this analysis (first request is waiting for a response before subsequent requests are made in parallel).

If you know the length of the charts response, you could parallelize the first and subsequent requests, since you only use key (index) and not the actual charts to perform the latter requests.

If the concerned with why the latter requests seem to take steadily increasing time to respond, that may be just a coincidence in complexity of each request, or, as user ctt@ pointed out in the comments, could indicate the backend is not handling the requests simultaneously. But that doesn’t seem to be the concern (per the comment).

[Vue.js] How to prevent Vue error Unknown custom element for namespaced HTML elements

I use vue.js in an environment where there is to output namespaced elements, let’s say <foo:aside> for example. Those elements are currently not even handled by vue.js in any way (binding values to attributes, adding event handlers, nothing like that), they are just present in the templates. However, they may contain children that must be handled and my contain mustache syntax to display variables, etc., so v-pre will disable those and is therefore not a solution for my usecase.

Everything works fine, but the console is flooded with the following error:

[vue.js warn]: Unknown custom element: <foo:aside> - did you register the component correctly?
For recursive components, make sure to provide the “name” option.

The namespace is defined on the root element via xmlns:foo, but that shouldn’t make a difference to vue.js anyway.

Is there any way to prevent this, by somehow telling vue.js to ignore namespaced elements or at least defining which namespaces should be allowed on ordinary HTML elements?

Solution :

You can use v-pre to tell vue.js that the element should be ignored, check vue.js api.

For example:

<foo:aside v-pre>

Solution 2:

Thanks to the linked possible duplicate (though I disagree that it’s a duplicate due to applying to a whole namespace and requiring child elements to work) and Silencesys’ comment, I ended up with this solution:

Vue.config.ignoredElements = [/^foo:/];

From vue.js 2.5 onwards, you can use regular expressions for ignoredElements, and that’s the perfect way to ignore a whole namespace without having to add every possible tag name, while still preserving vue.js functionality on those elements and their child elements.