link411 link412 link413 link414 link415 link416 link417 link418 link419 link420 link421 link422 link423 link424 link425 link426 link427 link428 link429 link430 link431 link432 link433 link434 link435 link436 link437 link438 link439 link440 link441 link442 link443 link444 link445 link446 link447 link448 link449 link450 link451 link452 link453 link454 link455 link456 link457 link458 link459 link460 link461 link462 link463 link464 link465 link466 link467 link468 link469 link470 link471 link472 link473 link474 link475 link476 link477 link478 link479 link480 link481 link482 link483 link484 link485 link486 link487 link488 link489 link490 link491 link492 link493 link494 link495 link496 link497 link498 link499 link500 link501 link502 link503 link504 link505 link506 link507 link508 link509 link510 link511 link512 link513 link514 link515 link516 link517 link518 link519 link520 link521 link522 link523 link524 link525 link526 link527 link528 link529 link530 link531 link532 link533 link534 link535 link536 link537 link538 link539 link540 link541 link542 link543 link544 link545 link546 link547

[Vue.js] Vue 2.0 click event from inside component not registering

there is a vue.js app, which has a component in it that represents the whole page. Inside that component, there is another component which represents (for example) a menu. Inside that menu, there is a button with a @click handler that vue.js is supposed to handle. However, that is not happening, and I’m going mad. Please help!

there is a blue bordered button that you are supposed to click for the EXPAND text to change. The components work just fine, and the text is rendered differently when I change the value of the ‘expanded’ property in the menu component. But I cannot get that value to change as a result of the click.

Vue.component(‘vuemenu’, {
template: ‘#menu-template’,
data: function() {
return {
expanded: false
}
},
methods: {
expand: function() {
this.expand = !this.expanded;
}
}
})

Vue.component(‘page’, {
template: ‘#page-template’,
methods: {
}
})

new Vue({
el: ‘#app’,
data: {
},
methods: {
}
})
.expanded {
background-color: red;
color: white;
font-size: 72px;
}

.clickme {
padding: 10px;
border: 1px solid blue;
cursor: pointer;
}
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id=”app”>
<page></page>
</div>

<template id=”page-template”>
<div id=”page”>
Here is the menu
<vuemenu></vuemenu>
And here is the rest of the page
</div>
</template>
https://stackoverflow.com/questions/ask#
<template id=”menu-template”>
<div id=”menu”>
Menu
<div class=”clickme” @click=”expand”>
click
</div>
<div :class=”{‘expanded’: expanded}”>
EXPAND
</div>
</div>
</template>

Solution :

There is an error in this code

Vue.component(‘vuemenu’, {
template: ‘#menu-template’,
data: function() {
return {
expanded: false
}
},
methods: {
expand: function() {
this.expanded = !this.expanded; // this.expanded not this.expand
}
}
})

Vue.component(‘page’, {
template: ‘#page-template’,
methods: {
}
})

new Vue({
el: ‘#app’,
data: {
},
methods: {
}
})

[Vue.js] Better approach handling 'Do not mutate vuex store state outside mutation handlers' errors

Beforehand: My application is working as intended, but to know if there’s an better approach to the problem, I was having.

Situation: there is a project where when currently implemeneting a Permission-System. The current flow is, to load specific objects (lets take user in this case) and inject the permissions afterwards.

Problem: Getting ‘Do not mutate vuex store state outside mutation handlers.’ error inside vuex-action.

Question: Is there a better way to omit the error than my approach below?

Simplified it looks like this (here when getting my objects from our API and storing them in vuex-store):

// user.js (vuex-module)
state: {
user: null,
},
mutations: {
// …
setUser(state, user) {
state.user = user
}
}
actions: {
// … other vuex-actions
async login({commit, dispatch}, payload) {
let userFromDb = DbUtil.getUser(payload) // is an axios call to our api

// here the permissions get injected
// action in another vuex-module
dispatch(‘permissions/injectPermissions’, userFromDb)

// commiting to store
commit(‘setUser’, userFromDb)

return userFromDb
}
}

My permissions.js (here when injecting the permissions to my object):

// permissions.js (vuex-module)
actions: {
// … other vuex-actions

// payload = user in this example
async injectPermissions({commit, dispatch}, payload) {
let permissionFromDb = DbUtil.getPermissions(/* … */)

payload.permissions = permissionFromDb // -> Here when getting ‘Do not mutate vuex store state outside mutation handlers.’-Error, because `payload` == the user from user-state

return payload
}
}

Workaround: I added a mutation which changes the user-state object for me inside a mutation-handler.

mutations: {
/**
* A ‘set’-wrapper to mutate vuex-store variable inside a mutation to avoid getting a error.
* @param state
* @param payload:
* object - object to be mutated
* prop - prop inside object that is affected
* value - value that should be assigned
*/
setWrapper(state, payload) {
let { object, prop, value } = payload

object[prop] = value
}
}

The line where the error was thrown before gets changed to:

commit(‘setWrapper’, {
object: payload,
prop: ‘permissions’,
value: permissionFromDb
})

Solution :

Actions do not mutate the state.
Actions are there to perform asynchronous tasks.
When you want to change the state within an action, you have to rely on a mutation by using this synatx: commit(‘MUTATION_NAME’, payload)

Then:

MUATATION_NAME(state, payload) {
state.permissions = payload.permissions
}

This is the clean and right way.

[Vue.js] Getting a vue form to go to the next page after submit in laravel

I’m using both laravel and vue.js and I’m trying to get my vue.js form to go to another page when I’ve submitted, but the problem is that once it’s submitted it refreshes and goes back to the page it’s on instead of the other page.

When I check my network tab in the dev tools, it posted to the right page but it doesn’t show up in the browser

This is my vue.js

<template>
<div class=”container”>
<div class=”row justify-content-center”>
<div class=”col-md-8”>
<div class=”card”>
<div class=”card-header”>Example Component</div>

<div class=”card-body”>
I’m an Supplier Code Selection component.
<br>

<form @submit.prevent=”submit”>
<label for=”parent-product”>Parent Product</label>
<select name=”parent-product” id=”parent-product” class=”form-control” v-model=”selected_parent”>
<option>Please select the code</option>
<option v-for=”product in products” :value=”product.id”>
{ product.supplier_code }
</option>

<option v-for=”child in children” :value=”child.id”>
{ child.supplier_code }
</option>
</select>

<input type=”submit” class=”btn btn-primary” value=”Submit”>
</form>
</div>
</div>
</div>
</div>
</div>
</template>

<script>
import axios from ‘axios’

export default {
props: [
‘products’,
‘children’,
‘selected_parent’
],

mounted() {
console.log(‘Component mounted.’)
},

methods: {
submit(){
var formData = new FormData();

console.log(‘this is the select box - ‘+this.selected_parent);
formData.append(‘parent-product’, this.selected_parent);

return axios.post(‘/add-to-cart/‘+this.selected_parent, formData);
},
},
}
</script>

My route

Route::any(‘/add-to-cart/{id}’, ‘PublicController@getAddToCart’)->name(‘product.addToCart’);

My controller function

public function getAddToCart(Request $request, $id)
{
$menus_child = Menu::where(‘menu_id’, 0)->with(‘menusP’)->get();
$contacts = Contact::all();

$product = Product::find($id);

$supplier_code = $request->supplier_code;

$oldCart = Session::has(‘cart’) ? Session::get(‘cart’) : null;

$cart = new Cart($oldCart);
$cart->add($product, $product->id, $supplier_code);

$request->session()->put(‘cart’, $cart);

return view(‘public.shopping-cart’, [‘products’ => $cart->items, ‘totalPrice’ => $cart->totalPrice, ‘menus_child’ => $menus_child, ‘contacts’ => $contacts, ‘supplier_code’ => $supplier_code]);
}

Solution :

You could just add a location if the axios call returns success. Ps. untested code.

methods: {
submit(){
var formData = new FormData();

console.log(‘this is the select box - ‘+this.selected_parent);
formData.append(‘parent-product’, this.selected_parent);

return axios.post(‘/add-to-cart/‘+this.selected_parent, formData)
.then(response => { location: ‘/‘});
},

Solution 2:

I found my issue. I forgot to change

return view(‘public.shopping-cart’, compact(‘supplier_code’));

to

return [‘redirect’ => route(‘product.shoppingCart’)];

in my laravel controller function

[Vue.js] Vue webpack is adding #/ to all URLs

when following along with some vue.js projects using vue.js init webpack test, but it seems like when running npm run dev, there is always a #/ appended to all urls.

This is also true for when I create a new component and route to it. If i do something like http://localhost:8080/newpath, it becomes http://localhost:8080/newpath#/.

Is there a config variable I can set so that the #/ is not appended to every URL? Using regex to remove it on every URL seems really unwieldily.

when not including any actual source code because this is from the HelloWorld app that vue.js init creates.

when using the latest versions for vue.js cli 3.

Solution :

From the docs on HTML5 History Mode:

The default mode for vue-router is hash mode - it uses the URL hash to
simulate a full URL so that the page won’t be reloaded when the URL
changes.

So you need to change the vue.js router to use the HTML5 history mode:

const router = new VueRouter({
mode: ‘history’,
routes: […]
});

Please also continue reading the docs beyond that because you will need to adjust the actual server configuration to support this mode so that users will be sent to the appropriate location if they copy and paste the address bar URL to a new tab.

[Vue.js] Vue not recognizing vue.config.ts in vue cli 3 and axios

We have vue.js application running on port 8081 and backend is on port 8080. We have configured vue.config.ts to fix the CORS issue and the code is as below. None of these is working and when the API call is made, we see front end port :
http://localhost:8081/account-api/owner

Im not sure whether the config in Vue.config.ts is not recognized in Vue. there is followed the documentation from Vue.

Here is my sample project: https://github.com/forTechGig/Vue.git

Please help.

//vue.config.js file.

module.exports = {
publicPath: “http://localhost:8080",
devServer: {
proxy: {
“/account-api”: {
target: “http://localhost:8080",
ws: true,
changeOrigin: true,
agent: proxyConfig.httpProxyAgent(),
pathRewrite: {
“^/account-api”: “/account-api”
}
}
}
}
};

Solution :

There are a few problems with the code. You’re using apostrophes instead of quotes, you’re missing commas. try this instead:

module.exports = {
publicPath: “http://localhost:8080",
devServer: {
proxy: {
“/account-api”: {
target: “http://localhost:8080",
ws: true,
changeOrigin: true,
agent: proxyConfig.httpProxyAgent(),
path,
Rewrite: {
“^/account-api”: “/account-api”
}
}
}
}
};

[Vue.js] jQuery data-table has problem with Vue.js

when using jQuery data-table in Vue.js in a laravel project. the data has reloaded well in data-table. but the problem is the data retrieve after loading data-table. because, in the first row of data-table says “there is not any data”!! what should i do to use jQuery data-table in Vue.js?

app.js file:

export const platform= {
el:’#platform’,

data: {
name:’’,
platforms: [],
},

methods: {
index:function() {
axios.get(‘/api/platforms’, {
headers: headers
}).then(response => {
this.platforms = response.data.data;
this.dataTable.row.add([
this.platforms
]);
}).catch(error => {
alert(error.response.data.message);
})
},

store:function() {
axios.post(‘/api/platforms’, {
params: {
name: this.name
}
}, {
headers: headers
}).then(response => {
this.platforms.push(response.data.data);
alert(response.data.message);
}).catch(error => {
if (error.response.status === 422) {
this.message = error.response.data.data[‘validation-errors’][‘params.name’];
} else {
this.message = error.response.data.message;
}
})
},
},

mounted:function() {
this.index();
},
};

the platform.blade.php file:

<section class=”content” id=”platform”>
<div class=”form-group”>
<input type=”text” v-model=”name”>
</div>
<button class=”btn btn-raised” @click.prevent=”store()”>save</button>

<div class=”row”>
<table class=”table table-bordered table-striped table-hover dataTable”>
<thead>
<tr>
<th>platform name</th>
</tr>
</thead>
<tbody>
<tr v-for=”(platform, index) in platforms”>
<td>@{ platform.name }</td>
</tr>
</tbody>
</table>
</div>
</section>

Solution :

For Reactivity you must initialize platforms in data() section to setup all necessary getters/setters - that is done by vue.js under the hood.

And assign a new array reference in this.platforms when updating with API response.

data: {
name:’’,
platforms: []
},


index:function() {
axios.get(‘/api/platforms’, {

}).then(response => {

// assign a new array reference in ‘this.platforms’
this.platforms = [ …response.data.data];

}).catch(…)
},


store:function() {
axios.post(‘/api/platforms’,


).then(response => {

// assign a new array reference in ‘this.platforms’
this.platforms = […response.data.data];
alert(response.data.message);
}).catch(…)
},
},

Solution 2:

ES6 supports this method…
`

<div class=”row”>
<table class=”table table-bordered table-striped table-hover dataTable”>
<thead>
<tr>
<th>platform name</th>
</tr>
</thead>
<tbody>
<tr v-for=”(platform, index) in platforms”>
<td>@{ platform.name }</td>
</tr>
</tbody>
</table>
</div>
</section>
</template>

<script>
import HelloWorld from “./components/HelloWorld”;

export default {
name: “App”,
data(){
return{
name:’’,
platforms: [],
}
},
methods: {
index:function() {
axios.get(‘/api/platforms’, {
headers: headers
}).then(response => {
this.platforms = response.data.data;
this.dataTable.row.add([
this.platforms
]);
}).catch(error => {
alert(error.response.data.message);
})
},

store:function() {
axios.post(‘/api/platforms’, {
params: {
name: this.name
}
}, {
headers: headers
}).then(response => {
this.platforms.push(response.data.data);
alert(response.data.message);
}).catch(error => {
if (error.response.status === 422) {
this.message = error.response.data.data[‘validation-errors’]
[‘params.name’];
} else {
this.message = error.response.data.message;
}
})
},
},
mounted:function() {
this.index();
},
components: {
HelloWorld
}
};
</script>`

Error in mounted hook: “ReferenceError: axios is not defined” you will face this error…..ESLINT should install and want to define axis method

[Vue.js] Nuxt + Vue + Axios + Enviroment Variables

when unable to provide axios a baseUrl using an enviroment variable

when using nuxt/vue/axios

What there is is roughly:

// axios.js

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

axios.defaults.baseURL = process.env.BASE_URL
Vue.use(VueAxios, axios)

and

// index.vue.js (front page as it appears on the client)

populateFilters () {
Vue.axios.get(‘filters’).then((response) => {
this.$store.commit(‘data/filters’, response.data)
})
.catch((e) => {
console.error(e)
})
}

and inside nuxt.config.js

// nuxt.config.js
build: {
extractCSS: true,
extend (config, ctx) {
// Run ESLint on save

const envLoad = require(‘dotenv’).config()

if (envLoad.error){
throw result.error
}
}
},

console.log(process.env.BASE_URL) prints the correnct connection string in CMD, however, in chrome web browser it outputs “undefined” and I get the following error

GET http://localhost:3000/filters 404 (Not Found)

meaning that axios (probably) defaults to http://localhost:3000 whenever the baseUrl for axios has not been set.

What I think the problem is

The server/client pair that is loaded up by nuxt has different contexts or that the server loads up axios before the enviroment variables have been loaded

What I need

I need to be able to either:

create .env files that contains (amongst other things) the BASE_URL
define these enviroment variables somewhere in the code (nuxt.config.js ?)

Solution
Please see the accepted answer

In addition, install nuxtjs/dotenv

npm install @nuxtjs/dotenv

and make the nuxt.config.js look like:

// nuxt.config.js
require(‘dotenv’).config()

module.exports = {

modules: [
‘@nuxtjs/dotenv’,
‘@nuxtjs/axios’,
],

axios: {
baseURL: process.env.BASE_URL
},
}

note that require(‘dotenv’).config() must be at the top

Solution :

Theres a nuxt axios module you can use. You can declare it in the module sectiont of the nuxt.config.js so you dont need the file axios.js. This is described here https://github.com/nuxt-community/axios-module#usage

By loading it in the modules in the nuxt.config.js file you will have the axios instance accesible with this.$axios in the components.

You can declare the base url in the nuxt.config.js

modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
[‘@nuxtjs/axios’, {
baseURL: ‘http://jsonplaceholder.typicode.com'
}]
],
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
},

For “other environement variables” you can use the vuex store to have them available to all components.

[Vue.js] How to acces Heroku config vars with Nuxt.js app

there is deployed my app on Heroku and on start of my app I check a config file and in there to access a config var there is created on Heroku API_KEY to define my Firebase config:

module.exports = {
fireConfig: {
apiKey: process.env.API_KEY,
authDomain: “emy-app.firebaseapp.com”,
databaseURL: “https://my-app.firebaseio.com",
projectId: “elec-tricks”,
storageBucket: “my-appappspot.com”,
messagingSenderId: “my id number”
}
};

this process.env.API_KEY is undefined. Should I use a different way to access it?

Solution :

You can define environment variables in the nuxt.config.js file, e.g.

export default {
env: {
firebaseApiKey: process.env.API_KEY || ‘default value’
}
}

Here we use the API_KEY environment variable, if it’s available, and assign that to firebaseApiKey.

If that environment variable isn’t set, e.g. maybe in development (you can set it there too if you want), we fall back to ‘default value’. Please don’t put the real API key in ‘default value’. You could use a separate throwaway Firebase account key here or just omit it (take || ‘default value’ right out) and rely on the environment variable being set.

These will be processed at build time and then made available using the name you give them, e.g.

module.exports = {
fireConfig: {
apiKey: process.env.firebaseApiKey, # Not API_KEY
// …
};

[Vue.js] how to listen to event's from bootstrap-vue modal?

i have to modal in my page and i need a way to listen to ‘ok’ event when pressing ok button on first modal and respond by opening the another modal.
there is no examples in the documentation .
https://bootstrap-vue.js.org/docs/components/modal/

i wanted to use this listner but nothing is explained and i couldn’t find out what is what here

export default {
mounted() {
this.$root.$on(‘bv::modal::show’, (bvEvent, modalId) => {
console.log(‘Modal is about to be shown’, bvEvent, modalId)
})
}
}

this is the relevant part of my code:

<div>
<b-modal id=”modal-center-add-post” style=”width: 120px” centered class=”h-50 d-inline-block min-vw-100” ok-title=”next” >
<add-post></add-post>
</b-modal>
</div>
<div>
<b-modal id=”modal-center-add-content” style=”width: 120px”
centered class=”h-50 d-inline-block min-vw-100”
ok-only ok-title=”Create” >
<add-content></add-content>
</b-modal>
</div>

and add-post componenet code is

<template>
<form>
<div class=”form-group row”>
<label for=”title”
class=”col-sm-2 col-form-label”>
Title
</label>
<div class=”col-sm-10”>
<input type=”text”
class=”form-control”
id=”title”
placeholder=”Title”>
</div>
</div>
<div class=”form-group row”>
<label for=”chooseTopic”
class=”col-sm-2 col-form-label”>
Topic
</label>
<div class=”col-sm-10”>
<select id=”chooseTopic” class=”form-control”>
<option selected>Leadership</option>
<option>HR</option>
<option>Sales</option>
<option>Marketing</option>
</select>
</div>
</div>
<fieldset class=”form-group”>
<div class=”row”>
<legend class=”col-form-label col-sm-2 pt-0”> Type</legend>
<div class=”col-sm-10”>
<div class=”form-check-inline “>
<label class=”form-check-label”
for=”video”
:class=”{‘checked’:(isChecked===’video’)}”
@click=”isChecked=’video’”>
<input class=”form-check-input”
type=”radio” name=”video”
id=”video”
v-model=”postingType”
value=”video” checked>
<i class=”fab fa-youtube “></i>
Video
</label>
</div>
<div class=”form-check-inline”>
<label class=”form-check-label”
for=”ebook”
:class=”{‘checked’:(isChecked===’ebook’)}”
@click=”isChecked=’ebook’”>
<input class=”form-check-input”
type=”radio”
name=”ebook”
id=”ebook”
v-model=”postingType”
value=”ebook”>
<i class=”far fa-file-pdf “></i>
Ebook
</label>
</div>
<div class=”form-check-inline “>
<label class=”form-check-label “
for=”article”
:class=”{‘checked’:(isChecked===’article’)}”
@click=”isChecked=’article’”>
<input class=”form-check-input “ type=”radio”
name=”article” id=”article”
v-model=”postingType” value=”article” >
<i class=”fas fa-pen-square “></i>
Article
</label>
</div>
</div>
</div>
</fieldset>

</form>
</template>

<script>
export default {
name: “AddPost”,
data(){
return{
postingType:’’,
isChecked:’video’
}
},

}
</script>

so when i click on ok (next ) in add-post component the second modal popup .

i hope the explanation was clear enough

thanks

Solution :

it’s right on the bottom of the documentation under Events

basicly use

@ok=”yourOkFn”