link685 link686 link687 link688 link689 link690 link691 link692 link693 link694 link695 link696 link697 link698 link699 link700 link701 link702 link703 link704 link705 link706 link707 link708 link709 link710 link711 link712 link713 link714 link715 link716 link717 link718 link719 link720 link721 link722 link723 link724 link725 link726 link727 link728 link729 link730 link731 link732 link733 link734 link735 link736 link737 link738 link739 link740 link741 link742 link743 link744 link745 link746 link747 link748 link749 link750 link751 link752 link753 link754 link755 link756 link757 link758 link759 link760 link761 link762 link763 link764 link765 link766 link767 link768 link769 link770 link771 link772 link773 link774 link775 link776 link777 link778 link779 link780 link781 link782 link783 link784 link785 link786 link787 link788 link789 link790 link791 link792 link793 link794 link795 link796 link797 link798 link799 link800 link801 link802 link803 link804 link805 link806 link807 link808 link809 link810 link811 link812 link813 link814 link815 link816 link817 link818 link819 link820 link821

[Vue.js] created hook for vuex / nuxtClientInit?

I was wondering whats the best way to do something like nuxtClientInit. I’m trying to load the Auth State as early as possible on the client and save it in my vuex store but not on the server side. It would be great if vuex had something like the created hook for components but that doesn’t exist to my knowledge.

How could I achieve this behavior? One way could be calling an action from a layout but is that the best way?

Solution :

I understand the nuxt team are working on a nuxtClientInit feature but before they release that you could just make the own. To understand the workflow that nuxt undertakes when there is a request you can look at the lifecycle here. This shows that nuxtServerInit is called first then middleware. During this middleware call nuxt.config.js is served and this contains the custom configuration. Part of this is ‘plugins’ which as the docs say,

This option lets you define JavaScript plugins that should be run
before instantiating the root Vue.js application.

So if you write a plugin to call a store action you can then get and set the local storage from there. So, start with a nuxt-client-init plugin:

//nuxt-client-init.client.js
export default async context => {
await context.store.dispatch(‘nuxtClientInit’, context)
}

then add the plugin to nuxt.config.js:

//nuxt.config.js
plugins: [
‘~/plugins/nuxt-client-init.client.js’
],

If you notice the naming convention here, the .client.js part of the plugin tells nuxt this is a client only plugin and is shorthand for ‘{ src: ‘~/plugins/nuxt-client-init.js’, mode: ‘client’ }’ which since nuxt 2.4 is the way to define the old ‘{ src: ‘~/plugins/nuxt-client-init.js’, ssr: false }’. Anyway, you now have a call to the store so you can have an action to call from local storage and set a state item.

//store/index.js
export const actions = {
nuxtClientInit({ commit }, { req }) {
const autho = localStorage.getItem(‘auth._token.local’) //or whatever yours is called
commit(‘SET_AUTHO’, autho)
console.log(‘From nuxtClientInit - ‘+autho)
}
}

You probably need to restart the app for that to all take effect but you are then getting and using the Auth State without any of that pesky nuxtServerInit business.

[Vue.js] hiding the vue routes

there is my vue.js routes as

const ifAuthenticated = (to, from, next) => {
if (store.getters.isAuthenticated) {
next()
return
}
next(‘/login’)
}

const checkAgentPermissions = () => {
return false
}

export const routes = [
{
path: ‘/users’,
beforeEnter: ifAuthenticated,
component: Layout,
meta: { title: ‘Agent Onboarding’, icon: ‘address-card’ },
hidden: checkAgentPermissions,
children: [
{
path: ‘’,
name: ‘Users’,
component: () => import(‘@/views/users/index.vue’)
},
{
…..some more childrens
}
]
}
]

but hidden is always true, when called through functions.
and if i change the option hidden from checkAgentPermissions to false

hidden: false // works perfectly

why function doesn’t return false, actually i need to do some check in fn and then return true/false depending on that.

forEach route when rendering them in vue.js component by checking if hidden is true/false.

Solution :

try to execute the hidden function:

hidden: checkAgentPermissions(),
children: [

[Vue.js] Vue how to pass a variable name as argument?

I’m trying to create a method to load download JSON files and assign the contents to a dynamic variable. I thought this should work, but varA and varB remain empty:

data() {
return {
varA: Array,
varB: Array
}
},

mounted(){
this.loadJSON(this.varA);
this.loadJSON(this.varB);
},

methods: {
loadJSON(uri, target) {
fetch(uri)
.then(res => res.json())
.then((out) => {
target = out;
})
.catch(err => {
throw err;
});
},
}

I’ve also tried to define varA and varB as computed properties, but that had the same result. How can can I do that without having to hardcode the variable names in loadJSON()?

Solution :

You can use Vue.set instead:

mounted(){
this.loadJSON(“varA”);
this.loadJSON(“varB”);
},

methods: {
loadJSON(uri, targetName) {
const self = this;
fetch(uri)
.then(res => res.json())
.then((out) => {
Vue.set(self, targetName, out);
})
.catch(err => {
throw err;
});
},
}

[Vue.js] VueJS Unknown Component

there is this code on the mounted hook

I’m using a component from Synfusion and I’ve initialize it in the mounted hook like so :

data() {
return {
treeViewInstance: {},
};
},
mounted() {
var data = [
{
nodeId: ‘01’, nodeText: ‘Music’,
nodeChild: [
{ nodeId: ‘01-01’, nodeText: ‘Gouttes.mp3’ }
]
},
{
nodeId: ‘02’, nodeText: ‘Videos’, expanded: true,
nodeChild: [
{ nodeId: ‘02-01’, nodeText: ‘Naturals.mp4’ },
{ nodeId: ‘02-02’, nodeText: ‘Wild.mpeg’ },
]
},
{
nodeId: ‘03’, nodeText: ‘Documents’,
nodeChild: [
{ nodeId: ‘03-01’, nodeText: ‘Environment Pollution.docx’ },
{ nodeId: ‘03-02’, nodeText: ‘Global Water, Sanitation, & Hygiene.docx’ },
{ nodeId: ‘03-03’, nodeText: ‘Global Warming.ppt’ },
{ nodeId: ‘03-04’, nodeText: ‘Social Network.pdf’ },
{ nodeId: ‘03-05’, nodeText: ‘Youth Empowerment.pdf’ },
]
},
];
//Initialize TreeView component
var treeViewInstance = new ej.navigations.TreeView({
fields: { dataSource: data, id: ‘nodeId’, text: ‘nodeText’, child: ‘nodeChild’ },
allowDragAndDrop: true,
});
this.treeViewInstance = treeViewInstance;
console.log(treeViewInstance);

//Render initialized TreeView
treeViewInstance.appendTo(“#tree”);

The problem is that the treeViewInstance in data properties have a weird value Unknown Component

I don’t know what to do to get the treeViewInstance in the data

Solution :

the component needs to be registered:
Component Registration

Something like this:

components:
{
my-component: myComponent
},

[Vue.js] How to open a single project like Behance with nuxt,js?

when working on a project using NUXT.JS where to open a project within a same page overlay somethink like behance. in other words when i click on a project to stop page redirection and open a project there in same place with a route but when someone comes to that route it will be a separate page.

I tried Nuxt nested routes with nuxt-child but didn’t work or i didn’t understand.

This is my structure

This is my project strucure

Solution :

You could create a component and import it in the index page as a modal window (so it gives the content of a modal-component), and also create a page where you import the same component as page content.

This way you can have it in the overlay and also as a separate page.

[Vue.js] Dynamic & Namespaced modules not registered (vuex-module-decorators, vuex-class)

The module is not registered:

$nuxt.$store._modulesNamespaceMap // No properties

Also, i’m getting this warning:

Classic mode for store/ is deprecated and will be removed in Nuxt 3.

What i’ve tried:

loading manually the module to see if the namespace was working (FAIL).
Try without namespace to load dynamically the module (FAIL).

Code:

// @/store/modules/User.ts
import { Module, VuexModule, Mutation, Action } from “vuex-module-decorators”;
import { firebase, auth, GoogleProvider, StoreDB } from “@/services/fireinit”;
import { IUser } from “~/types/user”;
import { store } from “..”;

// It seems like the “store” is fucked somehow
@Module({ dynamic: true, namespaced: true, store: store, name: “user” })
export default class User extends VuexModule {
user: IUser = null;

@Action
async autoSignIn(user: IUser) {
this.context.commit(“setUser”, user);
}

@Action
async signInWithGoogle() {
return new Promise(resolve => {
console.log(“signInWithGoogle:”, this);
auth.signInWithRedirect(GoogleProvider);
resolve();
});
}

// trunked …
}

// @/store/index.ts
import Vuex, { Store } from “vuex”;
import User from “./modules/User”;

// trunked …

// Declare empty store first
export const store = new Vuex.Store<IStoreType>({});

const createStore = () => store;

export default createStore;

// @/pages/login.vue

// trunked …

const User = namespace(‘user’); // [vuex] module namespace not found in mapActions(): user/

@Component({})
export default class LoginComponent extends vue.js {
@User.State(“activeUser”) stateUser;
@User.Action(“signInWithGoogle”) actionSignInWithGoogle;
}

Tree:

pages
login.vue
store
index.ts
modules
User.ts

I expect to be able to load dynamically & namespaced modules…

I tried everything i could find on the world wide web but i can’t manage to make it work.

What i’m doing wrong ?

Solution :

Ok, i found a way that work…

Code:

// @/store/index.ts
import Vuex, { Store } from “vuex”;
import User from “./modules/User”;

// trunked …

// Declare empty store first
export const store = new Vuex.Store<IStoreType>({});
// No more “createStore” shit.

// @/pages/login.vue

// trunked …

const User = namespace(‘modules/User/‘); // “modules/“ is important to make it work.

@Component({})
export default class LoginComponent extends vue.js {
@User.State(“activeUser”) stateUser;
@User.Action(“signInWithGoogle”) actionSignInWithGoogle;
}

[Vue.js] I build a app in Vue. I need to store information for later use, is it a good way to use js-cookie?

there is tried to use Vuex for storing information that the user choose in my app, but as soon i reload the page its gone. Then i started to use Cookies, js-cookie and its works perfect. I feel like that has to be something bad with it, why would you use vuex if you just could use a cookie?
there is not found any problems with using cookies but it feels at someway that is has to be something bad about it.

which way is best to go when you need to gather information and without it disappearing when you reload the page?

Solution :

Vuex is an in-memory storage. That gets cleared up as soon as the page reloads. You want a more persisted storage. There are several options, localstorage, sessionstorage, cookie and indexedDB.

Cookies are sent along with every request you make to the server. That is probably not necessary for you or what you want.

Localstorage should do just fine.

Check out vuex-persistedstate that synchronizes between Vuex and localstorage.

https://github.com/robinvdvleuten/vuex-persistedstate

That’s probably what you want to use.

Solution 2:

This is an example for local storage from https://vuejs.org/v2/cookbook/client-side-storage.html. This will store the car name even you close the session.

<div id=”app”>
My car <input v-model=”carName”>
</div>

const app = new Vue({
el: ‘#app’,
data: {
carName: ‘’,

},
mounted() {
if (localStorage.carName) {
this.carName = localStorage.carName;
}
},

watch: {
name(newName) {
localStorage.carName = carName;
}
}
});

[Vue.js] Vue.js add component option (prop) using custom directive

there is Custom component using my own directive (v-color):

<custom v-color=”color” />

And my script, which I define this.color and this.changeColor():

{
data () {
return {
color: red
}
},

methods: {
changeColor (color) {
this.color = color
}
}
}

How can I write the code of v-color directive to change v-bind:color of <custom />?

In other words, the value of v-bind:color will be red when the component is loaded. If this.color is modified by a method (such as this.changeColor(‘blue’)), value of v-bind:color would be auto-updated.

I would appreciate solutions that avoid “watch”, because I will use v-color many times.

Solution :

Something like this seems to fit what you’re looking for:

Vue.component(‘third-party-component’, {
props: [‘color’],
template: ‘<div :style=”{ color }” v-cloak>{color}</div>’
});

Vue.component(‘hoc-component’, {
props: [‘color’],
computed: {
transformedColor () {
if (this.color === “blu”) return “blue”;
if (this.color === “re”) return “red”;
if (this.color == “or”) return “orange”;
if (this.color == “pur”) return “purple”;
return this.color;
}
},
template: ‘<third-party-component :color=”transformedColor” />’
});

new Vue({
el: ‘#app’
});
<html>
<body>
<div id=”app” v-cloak>
<div>
<hoc-component color=”blu”></hoc-component>
<hoc-component color=”or”></hoc-component>
<hoc-component color=”re”></hoc-component>
<hoc-component color=”pur”></hoc-component>
<hoc-component color=”pink”></hoc-component>
<hoc-component color=”green”></hoc-component>
</div>
</div>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
</body>
</html>

Here we are taking advantage of the Higher Order Component pattern in order to modify the data we need and pass it on to the third party component. This is a much more effective way of mutating and handling data change without the side effects that directives have.

Hope this helps!

[Vue.js] Is it possible to set specific VueRouter props?

Working with VueRouter, to enable entrance to these URLs:

category/apple
category/banana
category/pear

Is it possible to limit a router parameter so certain strings? (banana, apple, pear)?

I cannot find anything in the documentation specifically about this. and I googled to find some other solutions that do not work:

{
path: ‘category/:categoryType’,
props: true,
/*props: {
validator: function (value) {
return ( value === ‘banana’ || value === ‘apple’ || value === ‘pear’);
}
},*/
component: someComponent
},

The only solution I can think of right now is to validate this in the created() within the component.

Solution :

I think this code is the solution of the case:

const allowedCategoryNames = [‘apple’, ‘banana’, ‘pear’];
const categoryRoutePath = ‘/category/:categoryName(‘ + allowedCategoryNames.join(‘|’) + ‘)’;
{
path: categoryRoutePath,
props: true,
component: someComponent
},

and in the component you can get current cutegory name like this:

const currentCategory = this.$route.params.categoryName;

That should work =)
Some examples can be found here: vue-router regexp examples

[Vue.js] How to deploy nodejs and vuejs to heroku

How can I can deploy my project to heroku.
My code base here:

I try to deploy to heroku but I always get an error.

-—-> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/nodejs.tgz

! ERROR: Application not supported by ‘heroku/nodejs’ buildpack
!
! The ‘heroku/nodejs’ buildpack is set on this application, but was
! unable to detect a Node.js codebase.
!
! A Node.js app on Heroku requires a ‘package.json’ at the root of
! the directory structure.
!
! If you are trying to deploy a Node.js application, ensure that this
! file is present at the top level directory. This directory has the
! following files:
!
! Procfile
! server/
! tsconfig.json
! vue/
!
! If you are trying to deploy an application written in another
! language, you need to change the list of buildpacks set on your
! Heroku app using the ‘heroku buildpacks’ command.
!
! For more information, refer to the following documentation:
! https://devcenter.heroku.com/articles/buildpacks
! https://devcenter.heroku.com/articles/nodejs-support#activation
More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
! Push failed

Can I change a heroku config to uses package file in sub folder?

Solution :

Please restructure the app, Heroku identity app by its app structure.
In the root directory there is not package.json file
Its best if you deploy back-end and front-end as separate apps

Hope this will help you. Happy Coding.