link2192 link2193 link2194 link2195 link2196 link2197 link2198 link2199 link2200 link2201 link2202 link2203 link2204 link2205 link2206 link2207 link2208 link2209 link2210 link2211 link2212 link2213 link2214 link2215 link2216 link2217 link2218 link2219 link2220 link2221 link2222 link2223 link2224 link2225 link2226 link2227 link2228 link2229 link2230 link2231 link2232 link2233 link2234 link2235 link2236 link2237 link2238 link2239 link2240 link2241 link2242 link2243 link2244 link2245 link2246 link2247 link2248 link2249 link2250 link2251 link2252 link2253 link2254 link2255 link2256 link2257 link2258 link2259 link2260 link2261 link2262 link2263 link2264 link2265 link2266 link2267 link2268 link2269 link2270 link2271 link2272 link2273 link2274 link2275 link2276 link2277 link2278 link2279 link2280 link2281 link2282 link2283 link2284 link2285 link2286 link2287 link2288 link2289 link2290 link2291 link2292 link2293 link2294 link2295 link2296 link2297 link2298 link2299 link2300 link2301 link2302 link2303 link2304 link2305 link2306 link2307 link2308 link2309 link2310 link2311 link2312 link2313 link2314 link2315 link2316 link2317 link2318 link2319 link2320 link2321 link2322 link2323 link2324 link2325 link2326 link2327 link2328

[Vue.js] How to send data from html (Django backend) to js (Vue frontend)

I’m developing a webpage. there is a login form in this webpage. I’m using Django for back-end and VueJS for front-end. To submit the form with Django, the requirement of Django is the CSRF Token. I currently can show the CSRF Token to HTML using { csrf_token }.

Because when using VueJS, I also use Vuetify to style the front-end. The CSRF Token is not visible to VueJS because VueJS doesn’t recognize { csrf_token } but HTML does.

After researching on the internet I found something. I tried using v-bind to give the CSRF Token from HTML to VueJS but unfurtunately the value of the v-bind is undefined. But if I go to my sourcecode (Ctrl+U), I can see that CSRF Toekn does work but VueJS does not recognize it.

Example:

<div id=”LoginApp”>
<WJLogin
v-bind:csrf=”8cl33zQ8pYXXEMVCoSsqIzaFgQkLh6WYXqsQMN4z9X4oGkSGN8Thz922jQ19aG4B”
v-bind:hello=”world”>
</WJLogin>
</div>

When I use v-bind from VueJS to VueJS this works but from HTML to VueJS doesn’t work

This is login.html

<div id=”LoginApp”>
<WJLogin
:csrf=”{csrf_token}”
:hello=”world”>
</WJLogin>
</div>

This is WJLogin.vue

export default
{
props: {
csrf: String,
hello: {
type: String,
default: “defaultValue”
},
},
…………..
…………

I expect the value of CSRF Token is accesable to VueJS.

Solution :

Dr. Harold Hardvard,

I don’t understand but the component is seen wrong.

Try this code please

<div id=”LoginApp”>
<WJLogin
:csrf=”csrf_token”
:hello=”world”>
</WJLogin>
</div>

<template>
<!– If it is fixed –>
<div>{ $props.csrf }</div>
</template>

<script>
export default {
name: ‘W3Login’,
props: {
csrf: String
},
// If it will be change.
computed: {
token() {
return this.$prop
}
}
methods: {
If using in any method.
x() {

this.$prop.csrf

}
}
}
</script>

Example link JsFiddle

Solution 2:

You shouldn’t use v-bind:csrf since when django render csrf_token, it will be literal (e.g. not a variable). V-bind is used to bind object into component prop. So do this:

index.html:

<div id=”LoginApp”>
<wjlogin
csrf=”{ csrf_token }”
hello=”world”>
</wjlogin>
</div>
<script src=”https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script> Vue.component('wjlogin', { template: \`<div>{ csrf }<br/>{ hello }</div>\`, name: 'wjlogin', props: { csrf: String, hello: { type: String, default: "defaultValue" }, }, }); new Vue({el: '#LoginApp'}) </script>

[Vue.js] Vuetify autocomplete - how to pass default value?

I’m using Vuetify autocomplete component and it to display a default value in its input field

I tried to pass just value as prop and change v-model field to any string but it doesn’t work - an input field is empty unless I choose value form the list

Vuetify official example

<v-autocomplete
v-model=”select”
:loading=”loading”
:items=”items”
:search-input.sync=”search”
cache-items
class=”mx-3”
flat
hide-no-data
hide-details
label=”What state are you from?”
solo-inverted
\></v-autocomplete>

new Vue({
el: ‘#app’,
data () {
return {
loading: false,
items: [],
search: null,
select: ‘Alabama’,
states: [
‘Alabama’,
‘Alaska’,
‘American Samoa’,
‘Arizona’,
‘Arkansas’,
‘California’,
‘Colorado’,
]
}
},
watch: {
search (val) {
val && val !== this.select && this.querySelections(val)
}
},
methods: {
querySelections (v) {
this.loading = true
// Simulated ajax query
setTimeout(() => {
this.items = this.states.filter(e => {
return (e || ‘’).toLowerCase().indexOf((v || ‘’).toLowerCase()) > -1
})
this.loading = false
}, 500)
}
}
})

Solution :

I think you should use v-combobox instead of v-autocomplete.

With Combobox, you can allow a user to create new values that may not
be present in a provided items list.

See the example of the difference between them here.

[Vue.js] Vuejs How to use $emit function properly?

there is two components SingleTaskItem and ControlArea. ControlArea has a collapse button and when that button is clicked to call a function in SingleTaskItem. Here is my code so far. Can you please tell me what am I doing wrong?

SingleTaskItem:
<template>
<div class=”SingleTaskItem”>
<ControlArea v-bind:collapsed=”collapsed”
v-bind:onClickCollapse=”onClickCollapse”/>
</div>
</template>

<script>
export default {
name: “SingleTaskItem”,
data() {
return {
collapsed: false
};
},
methods: {
onClickCollapse(value) {
console.log(“on Click Collapse called”);
this.collapsed = value;
}
}
};
</script>

ControlArea:

<template>
<div class=”ControlArea”>
<div class=”action-btn edit”>
<i class=”fas fa-ellipsis-h”></i>
</div>
<div class=”action-btn collapsible”>
<i v-if=”collapsed” v-on:click=”uncollapse” class=”fas fa-chevron-down”></i>
<i v-else v-on:click=”collapse” class=”fas fa-chevron-up”></i>
</div>
</div>
</template>

<script>
export default {
name: “ControlArea”,
props: {
collapsed: Boolean
},
methods: {
collapse(event) {
console.log(“collapse function is called”);
this.$emit(“onClickCollapse”, “true”);
},
uncollapse(event) {
this.$emit(“onClickCollapse”, “false”);
}
}
};
</script>

Solution :

Instead of v-bind:onClickCollapse=”onClickCollapse” you should use v-on:onClickCollapse. This is kind of easy to miss because you used the word ‘on’ in the event name - it might be clearer to remove that.

Also, to pass that true/false string you need to pass $event into the function call: v-on:onClickCollapse($event). To clean this up you should probably also pass true/false booleans rather than strings.

[Vue.js] Making global functions to access vuex store

so to make a global function that I can access in every component of mine. So I stumbled upon vue.js Plugins. They worked great, till I tried out my use case. I need to use some information from the vuex store in my plugin and return a true or false value.

So this is what there is tried

plugin.js

export default {
install (Vue) {
Vue.prototype.$rbac = (method, route) => {
$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route==route)
}
}
}

main.js

import plugin from ‘./utils/common/plugin’

Vue.use(plugin)

component.vue

<template>

<div v-if=”$plug(‘post’, ‘/project’)></div>

</template>

But I get an error saying “ReferenceError: $store is not defined”.

It kind of makes sense that I cannot access the store. The store only gets the value once the user logs in.

So is there any way I can make a global function that can access the store when it gets values?

Solution :

You’re getting the reference error because the $store variable hasn’t been defined anywhere. It’s not a local variable, nor is it a function parameter or global variable.

You probably meant to do this.$store; also make sure you use function () {} syntax and not () => {} because you don’t want to bind this.

export default {
install(Vue) {
Vue.prototype.$rbac = function (method, route) {
this.$store.state.generic.user.routes.some(m => m.method.includes(method) && m.route == route)
}
}
}

You could also use a global mixin to do a similar thing instead of a plugin.

[Vue.js] Infinite loop when using computed property with Vue Chart js

I’m trying to update my chart every 5 seconds with new data from an API call. My chart is updating but is rendering each point hundreds of times each. I checked the logs and it shows that there’s an infinite loop being caused and I’m not sure how to resolve this. Below is my current code:

Note: ‘graphData’ prop is an Array I’m passing from Parent that is data from API call that added to chart

ChildComponent.vue

<template>
<div class=”graphCard”>
<Linechart :chartData=”dataCollection” :options=”options” />
</div>
</template>

<script>
import Linechart from ‘@/utils/Linechart.js’

export default {
components: {
Linechart
},
props: [‘graphData’],
data() {
return {
collection: []
}
},
computed: {
dataCollection() {
this.collection.push(this.graphData[0])
return {
datasets: [
{
label: ‘chart’,
backgroundColor: ‘indigo’,
borderColor: ‘indigo’,
fill:false,
showLine: true,
data: this.collection
}]
}
},
options() {
return {
id: ‘Cumulative’,
legend: {
display: false
},
scales: {
xAxes: [{
type: ‘time’,
distribution: ‘series’,
time: {
displayFormats: {
millisecond: ‘mm:ss:SS’,
quarter: ‘MMM YYYY’
}
}
}],
yAxes: [{
ticks: {
//beginAtZero: true
}
}]
}
}
}

LineChart.js

import { Scatter, mixins } from ‘vue-chartjs’
const { reactiveProp } = mixins

export default {
extends: Scatter,
mixins: [reactiveProp],
props: [‘chartData’, ‘options’],
mounted () {
this.renderChart(this.chartData, this.options)
}
}

In an alternative approach I also tried to set up dataCollection and options as ‘data’ instead of ‘computed,’ with a watcher on the graphData prop, but the chart did not update and ran into an issue ‘Uncaught TypeError: Cannot read property ‘skip’ of undefined’

Solution :

Normally a computed is better than a watcher but I’m not sure I can debug this infinite loop without more context.
So here is the data + watch alternative who should work.

The code :

<template>
<div class=”graphCard”>
<Linechart :chartData=”dataCollection” :options=”options” v-if=”dataCollection.datasets[0].data.length”/>
</div>
</template>

<script>
import Linechart from ‘@/utils/Linechart.js’

export default {
components: {
Linechart
},
props: [‘graphData’],
data() {
return {
dataCollection: {
datasets: [{
label: ‘chart’,
backgroundColor: ‘indigo’,
borderColor: ‘indigo’,
fill:false,
showLine: true,
data: []
}]
},
options: {
id: ‘Cumulative’,
legend: {
display: false
},
scales: {
xAxes: [{
type: ‘time’,
distribution: ‘series’,
time: {
displayFormats: {
millisecond: ‘mm:ss:SS’,
quarter: ‘MMM YYYY’
}
}
}],
yAxes: [{
ticks: {
//beginAtZero: true
}
}]
}
}
}
},
watch: {
graphData (newData) {
this.dataCollection.datasets[0].data.push(newData[0])
}
}
}

[Vue.js] Vue.js lifecycle events and where to start loading store properties (Vue.observable)

I’m using Vue.observable() to manage state and need to wait for two store properties to be populated before most views are loaded by vue-router.

Tried putting the loading in the beforeCreate, created and mounted lifecycle events in App.vue.js since it’s the root of my web app:

<template lang=’pug’>

#app
AppHeader
router-view
AppFooter
</template>

<script lang=”ts”>
import { Component, vue.js } from ‘vue-property-decorator’;
import AppHeader from ‘@/components/AppHeader.vue’; // @ is an alias to /src
import AppFooter from ‘@/components/AppFooter.vue’;
import { mutations } from ‘@/store’;

@Component({
components: {
AppHeader, AppFooter
}
})
export default class App extends vue.js {
private async beforeCreate(): Promise<[void, void]> {
return await Promise.all([ mutations.clientSet(), mutations.productsSet()]);
}
}
</script>

But the vue-router loads the other views that depend on these state properties before the promises have a chance to resolve. All of my views are dependent on the properties being populated so moving return await Promise.all([ mutations.clientSet(), mutations.productsSet()]); to their lifecycle event handlers isn’t very efficient.

Is there a better place to run this code so it’s guaranteed to finish before the vue-router loads the views?

Solution :

I modified my store for each of the two properties to change them to promises (instead of the result). Anywhere I needed the values in views, I now await the values.

This allows the UI to load quickly and only wait where needed.

[Vue.js] Modify Image Url Value with Vue Js in a Loop

there is a simple Loop with conditionals. to modify the full url to a version of the image with 60x60 pixels.

Full image url : www.example.com/img/full-image-001.jpg .

Modified image url that I need : www.example.com/img/full-image-001-60x60.jpg .

<template v-else-if=”column === ‘product_img’”>
<img :src=”replaceLink.columnValue” alt=”” height=”60” width=”60”>
</template>

Method function:

methods : {
replaceLink (record) { //logic
}
}

EDIT :
Is this the proper way ?

methods: {
replaceLink (record) {
let res = record.replace(“.jpg”, “-60x60.jpg”);
console.log(res);
}
},

Solution :

Better solution is to create filter and use it on the images.

Instead fo methods object create filters object with replace function:

filters: {
replaceLink: function(value) {
if (!value) return ‘’;
return value.replace(‘.jpg’, ‘-60x60.jpg’);
}
}

And now in the HTML you can use it like this:

<img :src=”source | replaceLink” />

You should have source in the component data or you will get an error. This source should be image url

[Vue.js] VueJS + vue-i18n routing

Can’t figure out how to set up routing and why the current configuration doesn’t work.

What I’m trying to accomplish:

URL structure:

http://example.com/en
http://example.com/en/about-us
http://example.com/en/sample-page

http://example.com/fr
http://example.com/fr/about-us
http://example.com/fr/sample-page

To handle proper redirection I setup beforeEach:

router.beforeEach((to, from, next) => {
const lang = to.params.lang;

if ( ![‘en’,’fr’].includes(lang) ) {
return next(‘en’);
}

if ( i18n.locale !== lang ) {
i18n.locale = lang;
}

return next();
});

And here is the part which I do not understand, why it’s not working, why Home component not loading at all.

router.js

export default new Router({
mode: ‘history’,
base: process.env.BASE_URL,
routes: [
{
path: ‘/:lang’,
children: [
{
path: ‘’,
name: ‘home’,
component: Home,
}
],
},
],
})

Language (locale) switching working fine.

Solution :

You need a component to render route /:lang. You can create a file and add <router-view/> inside or create some anonymous component like:

export default new Router({
mode: ‘history’,
base: process.env.BASE_URL,
routes: [
{
path: ‘/:lang’,
component: {
render: h => h(‘router-view’)
},
children: [
{
path: ‘’,
name: ‘home’,
component: Home,
}
],
},
],
})

[Vue.js] Prop shows in Dev tools but shows undefined when used

I’m passing a simple ID down to a child component but have an undefined console log error and cannot use the prop

I pass the prop here to the child

<transactions v-show=”active_tab == 2” :userId=”affiliate.user_id”></transactions>

Which is then picked up in the child here

props: [“userId”]

I then just try and console log the prop like so

console.log(this.userId);

As you can see from the image the prop is showing up in Devtools

Error is as follows

[vue.js warn]: Invalid prop: type check failed for prop “userId”. Expected String with value “undefined”, got Undefined

Solution :

Try use the call on template like this:

<transactions v-if=”active_tab == 2” :user-id=”affiliate.user_id”></transactions>

The vue.js compilation can change camelcase props on template to lowercase with hyphen.

You can take a look on vue.js documentation about that: https://vuejs.org/v2/guide/components-props.html#Prop-Casing-camelCase-vs-kebab-case

Solution 2:

So it would seem the prop was being declared after page load, So there is used a Watch to wait for the change and then run the method

as so

watch: {
user_id() {
console.log(this.user_id);
this.fetch_transactions_data();
}
}

[Vue.js] How to pass TypeScript constants to Vue templates with least amount of reactivity

I’m wondering what’s the most performant way to pass a constant to a template. Currently, I’m using data, but as far as I understand, that should be mostly used for state that changes over time and vue.js adds event listeners to the data. The constants are just that - constant values that are used for output in templates, they’ll never change during the lifetime of the app.

<template>
<div>
<input type=”radio” name=”color” :value=Colors.GREEN />
<input type=”radio” name=”color” :value=Colors.RED />
</div>
</template>
<script lang=”ts”>
import vue.js from ‘vue’;
import Colors from ‘@/viewmodels/colors’;

export default Vue.extend({
name: ‘ExampleComponent’,
data() {
return () => {
Colors
}
}
})
</script>

Solution :

The decision is based on whether or not the value of Colors will change throughout the lifecycle of the component. If it won’t change, simply use a computed property:

Vue.config.devtools = false;
Vue.config.productionTip = false;

const Colors = {
GREEN: ‘#0F0’,
};
Vue.component(‘ExampleComponent’, {
name: ‘ExampleComponent’,
template: `
<div>
Value: <span style=”color:${Colors.GREEN}”>{ Colors.GREEN }</span>
</div>
`,
computed: {
Colors: () => Colors
}
})
new Vue({
el: ‘#app’,
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<example-component />
</div>

If you plan on changing it (based on user interaction or script), place it in data():

Vue.config.devtools = false;
Vue.config.productionTip = false;

const Colors = {
GREEN: ‘#0F0’,
};
Vue.component(‘ExampleComponent’, {
name: ‘ExampleComponent’,
template: `
<div>
Value: <span :style=”{color: Colors.GREEN}”>{ Colors.GREEN }</span>
<button @click=”changeColors”>Change Colors</button>
</div>
`,
data: () => ({
Colors
}),
methods: {
changeColors() {
this.Colors = {
GREEN: ‘red’
}
}
}
})
new Vue({
el: ‘#app’,
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<example-component />
</div>

If you want to allow the user to select one of the available options in Colors, it means Colors contents won’t change, therefore you’ll use a computed for Colors, along with a data() for currently selected color:

Vue.config.devtools = false;
Vue.config.productionTip = false;

const Colors = {
GREEN: ‘#090’,
RED: ‘#C00’,
BLUE: ‘#009’,
ORANGE: ‘#F90’
};
Vue.component(‘ExampleComponent’, {
name: ‘ExampleComponent’,
template: `
<div> Value:
<span
:style=”{color: currentColor, fontWeight: ‘bold’}”
v-text=”currentColor” />
<select v-model=”currentColor”>
<option
v-for=”(color, key) of Colors”
v-text=”\`\${key}: \${color}\`“
:key=”key”
:value=”color” />
</select>
</div>
`,
data: () => ({
currentColor: Colors.GREEN
}),
computed: {
Colors: () => Colors
},
methods: {
setColor(color) {
this.currentColor = color;
}
}
})
new Vue({
el: ‘#app’,
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<example-component />
</div>

You’ve updated the question with checkboxes. So I added an example using both checkboxes and radios, depending on what one might need:

Vue.config.devtools = false;
Vue.config.productionTip = false;

const Colors = {
GREEN: ‘#090’,
RED: ‘#C00’,
BLUE: ‘#009’,
ORANGE: ‘#F90’
};
Vue.component(‘ExampleComponent’, {
name: ‘ExampleComponent’,
template: `
<div> checkedColors:
<label v-for=”(color, key) of Colors”
:key=”key”>
<input name=”color”
type=”checkbox”
:value=”color”
v-model=”checkedArray”>
<span v-text=”color” :style=”{color}” />
</label>
<hr>
pickedColor:
<label v-for=”(color, key) of Colors”
:key=”color”>
<input name=”picked”
type=”radio”
:value=”color”
v-model=”picked”>
<span v-text=”color” :style=”{color}” />
</label>
<hr>
<pre>checkedArray: { stringify(checkedArray) }</pre>
<pre>picked: { picked }</pre>
</div>
`,
data: () => ({
checkedArray: [],
picked: Colors.GREEN
}),
computed: {
Colors: () => Colors
},
methods: {
stringify(value) {
return JSON.stringify(value, true, 2);
}
}
})
new Vue({
el: ‘#app’,
})
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<example-component />
</div>