link2055 link2056 link2057 link2058 link2059 link2060 link2061 link2062 link2063 link2064 link2065 link2066 link2067 link2068 link2069 link2070 link2071 link2072 link2073 link2074 link2075 link2076 link2077 link2078 link2079 link2080 link2081 link2082 link2083 link2084 link2085 link2086 link2087 link2088 link2089 link2090 link2091 link2092 link2093 link2094 link2095 link2096 link2097 link2098 link2099 link2100 link2101 link2102 link2103 link2104 link2105 link2106 link2107 link2108 link2109 link2110 link2111 link2112 link2113 link2114 link2115 link2116 link2117 link2118 link2119 link2120 link2121 link2122 link2123 link2124 link2125 link2126 link2127 link2128 link2129 link2130 link2131 link2132 link2133 link2134 link2135 link2136 link2137 link2138 link2139 link2140 link2141 link2142 link2143 link2144 link2145 link2146 link2147 link2148 link2149 link2150 link2151 link2152 link2153 link2154 link2155 link2156 link2157 link2158 link2159 link2160 link2161 link2162 link2163 link2164 link2165 link2166 link2167 link2168 link2169 link2170 link2171 link2172 link2173 link2174 link2175 link2176 link2177 link2178 link2179 link2180 link2181 link2182 link2183 link2184 link2185 link2186 link2187 link2188 link2189 link2190 link2191

[Vue.js] setCustomValidity() not working in Chrome browser

I’ve got a problem when I’m trying to set custom message in my input:

<b-form-input
v-model.number=”libpublishingdatefrom”
someprops…
oninvalid=”setCustomValidity(Vue.prototype.trans(‘validation.gte.numeric’))”
class=”inputdate”>
</b-form-input>

It’s working on Firefox browser but on Chrome oninvalid is ignored and it still displays custom message.

I’ve found one topic about version of Chrome HERE, but there is version 74. It’s possible they still have not fixed it?

Solution :

try with this one:

<b-form-input
v-model.number=”libpublishingdatefrom” oninvalid=”this.setCustomValidity(Vue.prototype.trans(‘validation.gte.numeric’))”
oninput=”this.setCustomValidity(‘’)”
class=”inputdate”>
</b-form-input>

[Vue.js] How to configure laravel-mix to be able to use @material with vue.js

I need some help with configuring material-web-components to work with vue.js components. The error occurs when to import a @material component scss into my vue.js component.

SomeVueComponent.js:

<style lang=”scss”>
@import ‘@material/textfield/mdc-text-field.scss’;
</style>

The error is that some @material components import other @material component scss, but cannot be found because of the includePaths, which I fixed by adding this code into my laravel-mix file:

webpack.mix.js:

mix.webpackConfig({
module: {
rules: [
{
test: /\.vue$/,
loader: ‘vue-loader’,
options: {
loaders: {
scss: ‘vue-style-loader!css-loader!sass-loader?’ + JSON.stringify({
includePaths: [‘node_modules’]
})
}
}
}
]
}
});

After saving this file everything compiles correctly but now I get this error for all of my vue.js components on the site:

[vue.js warn]: Failed to mount component: template or render function not defined.

After a whole day of researching on how to fix this, I found out that the conflict is generating because I push the vue-loader 2 times with webpack (The default one + my custom one).

Does anyone know a workaround on how to do this? It would be really helpful.

when using:

laravel 5.7.8
laravel-mix 4.0.15
vue.js 2.6.10
vue-loader 15.4.2
webpack 4.27.1

there is already tried the new way to import vue.js components after vue-loader v13+. (Adding the .default after the require) Still same vue.js error.

Vue.component(‘some-vue-component’, require(‘./components/SomeVueComponent.vue’).default);

Solution :

SomeVueComponent.js:

<style src=”@material/textfield/mdc-text-field.scss” lang=”scss”></style>

[Vue.js] Integrate ParticlesJs into a view component

to integrate ParticlesJs into my landing page. So only my home view should use this particles configuration and render particles.

I created a snippet and added the ParticlesJs dependencies

https://codesandbox.io/s/ol2rnrlxxq

Two problems come up:

I added the ParticlesJs file to the sandbox but the function particlesJS is not defined
I still want to have the content wrapped by v-layout in the center of the screen. How can I keep it? I wrapped the view with v-content because I think there is to add <div id=”particles-js”></div> on top level of the component

The final result should look like this.

I added the flat attribute to the card so fixing the two problems should make it work.

Solution :

You have to put the particlesJS initialize code in mounted hook instead of created. Because in created hook, DOM elements does not created yet. Please see more about mounted.

export default {
mounted () {
particlesJS(“particles-js”, {

})
}
}

To make particles-js fullscreen:

#particles-js {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: pink;
}

To make the layout center (from Layout grid system example):

<v-layout align-center justify-center row fill-height/>

codesandbox.io

[Vue.js] Changing class with VueJS for several cards

there is this page with several cards and each card has its own status radio buttons: ok, missing, error.

I wanna change the status of each card without changing others. So I created a method to change the class on @change event, but as all cards bind the same ‘data’, like ‘status’, changing one, changing all.

Lets see some code

<input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio1” value=”option1” @change=”ok”>
<input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio2” value=”option2” @change=”falta”>
<input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio3” value=”option3” @change=”erro”>

The script part:

var vue.js = new Vue({
el: ‘#app’,
data: {
status: ‘’
}

And the method() part:

ok() {
this.status = ‘bg-primary text-white’},
//will code some AJAX too
falta() {
this.status = ‘bg-warning text-black’},
//will code some AJAX too
erro() {
this.status = ‘bg-danger text-white’
//will code some AJAX too
}

The hole card deck code is:

<div class=”card-columns”>
<div class=”card” :class=”status”>
<div class=”card-body”>
<h5 class=”card-title”>Dados Cadastrais</h5>
<p class=”card-text”>
LOGRADOURO: @{ rua }, </p><p> NMERO: @{ numero }, </p><p> BAIRRO: @{ bairro }, </p><p> TEMPO DE RESIDNCIA: @{ tempoResidencia
}, </p><p> CIDADE: @{ cidade }, </p><p> UF: @{ uf }, </p><p> TELEFONE: @{ telefone }, </p><p> CELULAR: @{ celular }, </p><p> CEP:
@{ CEP }
</p>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio1” value=”option1” @change=”ok”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio2” value=”option2” @change=”falta”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosCadastrais” id=”inlineRadio3” value=”option3” @change=”erro”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card” :class=”status”>
<div class=”card-body”>
<h5 class=”card-title”>Dados do Bem</h5>
<p class=”card-text”>
CONTRATO: @{ contrato }, </p><p> GRUPO: @{ grupo }, </p><p> COTA: @{ cota }, </p><p> VALOR: @{ valor }, </p><p> PESSOA: @{ pessoa }, </p><p> BEM CONTRATADO: @{ segmento }, </p><p> BEM ESCOLHIDO: @{ novoSegmento }, </p><p> idERP: @{ idERP }, </p>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBem” id=”inlineRadio1” value=”option1” @change=”ok”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBem” id=”inlineRadio2” value=”option2” @change=”falta”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBem” id=”inlineRadio3” value=”option3” @change=”erro”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card” :class=”status”>
<div v-if=”contas != ‘’”>
<div class=”card-body”>
<h5 class=”card-title”>Dados Bancrios</h5>
<p class=”card-text”>
BANCO: @{ contas.banco }, </p>
<p> AGNCIA: @{ contas.agencia }, </p>
<p> CONTA CORRENTE: @{ contas.conta }, </p>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio1” value=”option1” @change=”ok”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div v-else>
<div class=”card-body”>
<h5 class=”card-title”>Dados Bancrios</h5>
<form v-on:submit.prevent=”sub” action=”#” method=”post”>
@method(‘POST’)
@csrf
<div class=”form-group”>
<label for=”banco”>Banco</label>
<input type=”text” v-model=”banco” class=”form-control” id=”banco”>
</div>
<div class=”form-group”>
<label for=”agencia”>Agncia</label>
<input type=”text” v-model=”agencia” class=”form-control” id=”agencia”>
</div>
<div class=”form-group”>
<label for=”conta”>Conta Corrente</label>
<input type=”text” v-model=”conta” class=”form-control” id=”conta”>
</div>
<button type=”submit” class=”btn btn-primary”>Cadastrar</button>
</form>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio1” value=”option1” @change=”ok”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosBancarios” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
</div>
<div class=”card”>
<div class=”card-body”>
<h5 class=”card-title”>Dados de Patrimnio</h5>
<p class=”card-text”>
AES: @{ patrimonios.valorAcoes }, </p>
<p> AUTOMVEIS: @{ patrimonios.valorAutomovies }, </p>
<p> IMVEIS: @{ patrimonios.valorImovel }, </p>
<p> INVESTIMENTOS: @{ patrimonios.valorInvestimentos }, </p>
<p> TOTAL: @{ patrimonios.valorTotal }, </p>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosPatrimonio” id=”inlineRadio1” value=”option1”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosPatrimonio” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosPatrimonio” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card”>
<div class=”card-body”>
<h5 class=”card-title”>Endereos de Patrimnios</h5>
<div v-for=”imovel in imoveis”>
<p class=”card-text”>RUA: @{ imovel.rua }, </p>
<p> NMERO: @{ imovel.nroReferencia }, </p>
<p> COMPLEMENTO: @{ imovel.complementoPatrimonio }, </p>
<p> BAIRRO: @{ imovel.bairroPatrimonio }, </p>
<p> CEP: @{ imovel.cep }, </p>
<p> CIDADE: @{ imovel.cidadePatrimonio }, </p>
<p> UF: @{ imovel.UFPatrimonio }, </p>
<hr>
</div>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endPatrimonio” id=”inlineRadio1” value=”option1”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endPatrimonio” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endPatrimonio” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card” v-if=”correspondencia != ‘’”>
<div class=”card-body”>
<h5 class=”card-title”>Endereo de Correspondncia</h5>
<div v-if=”correspondencia != ‘’”>
<p class=”card-text”>RUA: @{ correspondencia.rua }, </p>
<p> NMERO: @{ correspondencia.numero }, </p>
<p> BAIRRO: @{ correspondencia.bairro }, </p>
<p> CEP: @{ correspondencia.cep }, </p>
<p> CIDADE: @{ correspondencia.cidade }, </p>
<p> UF: @{ correspondencia.UF }, </p>
</div>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endCorrespondencia” id=”inlineRadio1” value=”option1”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endCorrespondencia” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”endCorrespondencia” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card”>
<div class=”card-body”>
<h5 class=”card-title”>Dados Profissionais</h5>
<p class=”card-text”>PROFISSO: @{ profissao.profissao }, </p>
<p> CARGO: @{ profissao.cargo }, </p>
<p> SALRIO: @{ profissao.salario }, </p>
<p> EMPRESA: @{ profissao.empresa }, </p>
<p> EMAIL: @{ profissao.emailEmpresa }, </p>
<p> CNPJ: @{ profissao.cnpj }, </p>
<p> RUA: @{ profissao.logradouro }, </p>
<p> CEP: @{ profissao.cep }, </p>
<p> Cidade: @{ profissao.cidade }, </p>
<p> UF: @{ profissao.UF }, </p>
<p> BAIRRO: @{ profissao.bairro }, </p>
<p> TELEFONE: @{ profissao.ddd } - @{ profissao.telefoneComercial } </p>
<p> RAMAL: @{ profissao.ramal }</p>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosProfissionais” id=”inlineRadio1” value=”option1”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosProfissionais” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”dadosProfissionais” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
<div class=”card”>
<div class=”card-body”>
<h5 class=”card-title”>Referncias Pessoais</h5>
<div v-for=”referencia in referencias”>
<p class=”card-text”>NOME: @{ referencia.nome }, </p>
<p> ENDEREO: @{ referencia.endereco }, @{ referencia.numero }</p>
<p> CIDADE: @{ referencia.cidade }, </p>
<p> UF: @{ referencia.UF }, </p>
<p> CEP: @{ referencia.cep }, </p>
<p> COMPLEMENTO: @{ referencia.complemento }, </p>
<p> TELEFONE: (@{ referencia.ddd }) @{ referencia.telefone }, </p>
<hr>
</div>
</div>
<div class=”card-footer text-muted”>
<div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”refPessoais” id=”inlineRadio1” value=”option1”> <label class=”form-check-label” for=”inlineRadio1”>OK</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”refPessoais” id=”inlineRadio2” value=”option2”> <label class=”form-check-label” for=”inlineRadio2”>Falta</label> </div> <div class=”form-check form-check-inline”> <input class=”form-check-input” type=”radio” name=”refPessoais” id=”inlineRadio3” value=”option3”> <label class=”form-check-label” for=”inlineRadio3”>Erro</label> </div>
</div>
</div>
</div>

How can I do it be as much as DRY as possible, and change only the card I wanna change?

Solution :

Add data elements:

data: {
oks: [],
faltas: [],
erros: []
}

Add some new logic to the methods:

falta(index) {
if (!this.faltas.includes(index)) {
this.faltas.push(index)
}

// other stuff
}

Repeat this for the erro() method.

Make sure you add the reverse logic for the ok() method:

if (this.erros.includes(index)) {
this.erros.splice(this.erros.findIndex(el => el === index), 1)
}

Dynamically change the card class based on the existence of the index:

<div class=”card” :class=”{‘bg-primary text-white’: this.faltas.includes(1)’}”>

Add any other conditionals there based on inclusion, such as for oks.includes(id) and errors.includes(id)

And update the methods for the input elements to pass the unique indexer for this card:

@change=”ok(1)”
@change=”falta(1)”
@change=”erro(1)”

And just change 1 to 2 for the next card and methods within that card and so on and so forth.

Solution 2:

You can use vue-refs to get a particular element.

Here is simple code to reproduce:

Template

<div class=”card” ref=”card-1”>
<div class=”card-body”>
…..
</div>
<div class=”card-footer text-muted”>
<input @click=”setClass(1, ‘bg-primary text-white’)”>
<input @click=”setClass(1, ‘bg-warning text-black’)”>
<input @click=”setClass(1, ‘bg-danger text-white’)”>
</div>
</div>

<div class=”card” ref=”card-2”>
<div class=”card-body”>
…..
</div>
<div class=”card-footer text-muted”>
<input @click=”setClass(2, ‘bg-primary text-white’)”>
<input @click=”setClass(2, ‘bg-warning text-black’)”>
<input @click=”setClass(2, ‘bg-danger text-white’)”>
</div>
</div>

Methods: {
setClass(index, className) {
const elem = this.$refs[`card-${index}`]
elem.className = className
}
}

Solution 3:

I would suggest to store the status on the object directly. For this to work the list used in the v-for must be inside the component data so it’s editable.

With this approach there is no need to track who has what status, indexes, etc. Each object is responsible for its own status. In this example I suppose there will be classes set up with correct styling, ok, falta and erro.

<div class=”card”>
<div class=”card-body” :class=”referencia.status”>
<h5 class=”card-title”>Referncias Pessoais</h5>
<div v-for=”referencia in referencias”>
<p class=”card-text”>
NOME: @{ referencia.nome }
</p>

<hr>
</div>
</div>
<div class=”card-footer text-muted”>
<button class=”some-styling-here” @click=”referencia.status = ‘ok’”> OK </button>
<button class=”some-styling-here” @click=”referencia.status = ‘falta’”> Falta </button>
<button class=”some-styling-here” @click=”referencia.status = ‘erro’”> Erro </button>
</div>
</div>

[Vue.js] Axios post request get body from catch?

there is post request with api:

axios.post(‘https://api.myapp.com:8000', formData).then(function (response) {
}).catch(function (error) {
console.log(error)
})

I get here response with “xhr” type. In console I see only:

Error: Request failed with status code 422
at createError (createError.js?2d83:16)
at settle (settle.js?467f:18)
at XMLHttpRequest.handleLoad (xhr.js?b50d:77)

to do something like error.data the push content into my alert bar.

What I tried is:
error.responseType, error.response, error.responseBody, error.status, for every of this calls I get simple undefined. Under network in console I see the content like needed.

How can I get content from such response?

Solution :

Change you catch statement like the following. I hope it will work.

.catch (error) {
console.log(error);
}

Solution 2:

I found this solution and it works for me:

axios.post(‘https://api.myapp.com:8000', formData).then(response => {
console.log(response)
}).catch(error => {
console.log(error.response)
})

[Vue.js] Is there a way to store a reference to a specific component within the DOM?

The problem:

when currently working on a file tree, more specifically on a “Selected Folder” functionality. I’m doing this to have a specific target for creating new files and folders, other that the root folder. (I’m using vue.js within Electron, but this is not really relevant to the question)

Selection happens on click. Due to the nature of file trees, I use recursive components (and this limits my ‘easy’ access to some components).

While achieving this on the back-end is trivial, my exact problem is that while marking the selected folder with, say a different background color or bold text (by binding an id or class that has some corresponding style on my stylesheet), I need to unmark the previously selected directory.

So, how do I gain access to an indirect (due to the recursive components) child component?

What I’ve tried, and looked into:

Now, I know that within JS you can’t store pointers or references in variables (otherwise this would’ve been easily achieved by storing a reference to the previous DOM element).

there is some solutions up my sleeve, but they’re really tedious and not very straightforward. Previously, I had to re-render (by re-reading) specific sub-directories, based on file system updates. I achieved this partial re-rendering by propagating child function calls from the root directory until I reached the directory that needed to be re-rendered. I had to do this since the FS watcher was created on the root component.

Similarly, I could do this with the un-marking task. When I select the new folder, I start by propagating child function calls until I reach the previously selected folder, and un-mark it by un-binding the style id. Having done this previously, I know it’s not a pleasant method.

Since I can get the click event target, I wondered if I could somehow store any kind of reference to the previously ‘selected’ DOM element and just use that reference later when I need to ‘deselect’ it.

Here’s what my folder component looks like. I tried giving self-explanatory names to the properties, but if there’s any confusion, I’ll answer any question.

<folder-comp
@openFile=”openFile”
v-for=”folder of folders”
:key=”`folder-${folder.shortFolderName}`“
:folder-name=”folder.shortFolderName”
:ref=”folder.shortFolderName”
:full-folder-path=”folder.fullFolderPath”
:local-directory=”recursiveScanDir”
:indentation-level=”indentationLevel + 1”>
</folder-comp>

The propagation method I used was necessary previously since all I had was an event File System path, unrelated to my vue.js structures, and so I needed to somehow translate traversing that path. Here, though, everything happens only within the vue.js environment, so I thought there would be some sort of way to deal with this easily.

EDIT: Well, as it happened with me in the past, just writing about the problem itself on stackoverflow helped me reach a solution.

there is a Global Event Bus set up on my vue.js project, so I can bind an event listener on the currently selected folder. Once another folder is clicked (thus selected), it emits an event in the Global Event Bus, triggering the previously selected folder. This is followed by the un-marking and the unbinding of the event listener.

This is only one solution though, so the question still stands. Is this a good solution? Are there any drawbacks to this approach? Is there a better solution?

Solution :

Instead of a global event bus, you can also use state management such as Vuex. When you change folders, you simply dispatch an action. This uses an command pattern, as opposed the the mentioned listener pattern. You have the choice to make this action asynchronous or synchronous as well.

There are several ways to register the listeners/watchers, from within components, or outside of them.

Using this architecture will allow you to easily add undo/redo capabilities, and also be able to navigate back and forth through the history of mutations.

You also gain the integrated debug features provided by the vue.js tools in the browser.

In fact, Vuex was built exactly for situations like this, when components need to communicate with each other but the parent/child prop/emit/inject mechanisms start to become tedious and and fall apart.

There is a high probability that once you starting using Vuex, you will never look back.

[Vue.js] Issue with method not returning values in interpolation nuxjs/vue

In my nuxtjs app static folder there is a file called data.json

in my component I use this data like so

<script>
import data from ‘~/static/data.json’;
export default {
data ({ params }) {
return {
data
}
}
}
</script>

now there is a method that will basically take values from that data and create a little counting up animation like so

methods: {
countUp(value) {
for (let i = 0; i <= value; i++) {
setTimeout(() => {
return i;
}, 100);
}
}
}

and in my template when calling it like so

<template>
<div>
<p>{countUp(data.number)}</p>
</div>
</template>

now the expected result is for the number to quickly change from 0 to the value but nothing is being printed on the dom if I inspect the html element its empty??

What am I doing wrong??

Solution :

setTimeout doesn’t work the way you think it does:

You can’t return a value from inside the callback function; nothing is being returned from the countUp method.
The call to setTimeout doesn’t block, meaning it will return immediately after being called and the callback function passed to it is scheduled for execution asynchronously after the timeout has passed. So every setTimeout call in the for loop will be executed all at once after 100 ms instead of staggered.

You will need to store the current counter value as data on the component so vue.js knows to rerender when its value is changed.

The simplest example I can provide follows, but you might want to encapsulate the logic in a separate reusable component.

const value = 50

new Vue({
el: ‘#app’,

data: {
counter: 0,
},

methods: {
countUp() {
const interval = setInterval(() => {
this.counter++

if (this.counter >= value) {
clearInterval(interval)
}
}, 100)
}
}
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<button @click=”countUp”>Count Up</button>
{ counter }
</div>

[Vue.js] Vue js with debug package

I’m trying use debug package in my vue.js project.
there is done some steps but didn’t work:

installed package : npm install debug
set debug module in vue.js component:

<script>
import debug from ‘debug’

const log = debug(‘app:logging’)

export default {

created(){
log(‘testing logging’);
}

}
<script>

did run the project in VS Code powershell: $env:DEBUG=’app:*‘; npm run serve
did try cmder with set DEBUG=app:* & npm run serve
did try set DEBUG in .env file got message [dotenv][DEBUG] “DEBUG” is already defined in “process.env” and will not be overwritten

What should I do to get this working corectly? I would like to see the message testing logging in console.

Solution :

Just read the documentation:

var log = debug(‘app:log’);
// set this namespace to log via console.log
log.log = console.log.bind(console); // don’t forget to bind to console!
log(‘goes to stdout’);

[Vue.js] Not import module with Vue.js if using Internet Explorer

When I build my Vue.js application with vue-cli-service-build, I get a blank page with Internet Explorer (but it works with Firefox and Chrome).
I know the problme is related to CKEditor, since it is not supported by IE.
However, I created a condition that only “requires” CKEditor if we’re not using IE. This solution works with vue-cli-service-serve, but not vue-cli-service-build.

if(!usingIE())
{
alert(“not using ieee”);
CKEditor = require(‘@ckeditor/ckeditor5-vue’).component;
ClassicEditor = require(‘@ckeditor/ckeditor5-build-classic’);

}
else
{
alert(“using IE”);
}

If I comment the two lines that “requires” CKEditor modules and build the app, it works with IE.

If I put false inside the condition but do not comment the two lines, it works with IE too. However, that’s not what I want, because I need to allow users to use CKEditor if they’re using Chrome/Firefox.

if(false)
{
alert(“not using ieee”);
CKEditor = require(‘@ckeditor/ckeditor5-vue’).component;
ClassicEditor = require(‘@ckeditor/ckeditor5-build-classic’);
}

to know if I’m using the proper way to include modules that are not supported by a browser. Otherwise, what is the best way to do that?

Solution :

You can try to use v-if and v-else block to conditionally render the component.

Example:

<div v-if=”type === ‘A’”>
A
</div>
<div v-else-if=”type === ‘B’”>
B
</div>
<div v-else-if=”type === ‘C’”>
C
</div>
<div v-else>
Not A/B/C
</div>

References:

(1) Conditional Rendering

(2) Conditional component rendering

(3) Vue.js router - conditional component rendering

[Vue.js] How to get data from URI in js in a synchronous way

I’m trying to get data from a uri. I use the exemple at :
https://jsonplaceholder.typicode.com/users/1
and try to display the id (“id” : “1”).
there is to get this value into a variable because I’m also using vuejs template.

Is there a simple way to get a cute little data ?

I tried Promises, and XMLHttpRequest, but send() throws error “fs.writeFileSync is not a function”, and I failed to synchronise Promises…

There is my code before the export for vuejs template :

var XMLHttpRequest = require(“xmlhttprequest”).XMLHttpRequest;
var fs = require(‘browserify-fs’);
var xhr = new XMLHttpRequest();

function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}

/*function succes(msg){
console.log(‘ok : ‘+msg);
changeAffichage(msg);
}
function echec(msg){console.log(‘ko : ‘+msg); changeAffichage(“error”);}
function uri(){
return fetch(‘https://jsonplaceholder.typicode.com/users/1')
.then(function(response){
return response.json()
.then(function(value) {
console.log(‘value : ‘);
console.log(value);
console.log(‘id = ‘+value.id);
return value.id;
}).catch(function(error) {
console.log(‘Il y a eu un problme avec l\‘opration fetch: ‘ + error.message);
});
}).catch(function(error) {
console.log(‘Il y a eu un problme avec l\‘opration fetch: ‘ + error.message);
});
}*/
function changeAffichage(msg){
window.affichage=msg;
console.log(“new affichage : “+window.affichage);
}
window.affichage=”Meow”;
//Promise.all([uri()]).then(succes, echec);

sleep(200);

xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://jsonplaceholder.typicode.com/users/1', false);
xhr.send(null);
if (xhr.status === 200) {
console.log(“Rponse reue: %s”, xhr.responseText);
} else {
console.log(“Status de la rponse: %d (%s)”, xhr.status, xhr.statusText);
}
changeAffichage(xhr.responseText);

console.log(‘affichage final = ‘ + window.affichage);

to get the value of id into window.affichage, please :(

Solution :

I don’t understand what is the purpose with vue.js here, but you if you want to make an http request you can do it with vue-axios package and assign the result of the http request to reactive property