Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

change # symbol to #! vue js router

Sun, 2017-08-13 02:43

my client wants to use AJAX crawling https://developers.google.com/webmasters/ajax-crawling/docs/specification (I know that it is deprecated But he wants it to use because of another search engine that still support it such as yandex.ru)

So I want to translate http://example.com/#/card/card_slug?category=car

to http://example.com/#!/card/card_slug?category=car

How do I do this with vue-router?

Categories: Software

Webpack doesn't compile Vue components corrently?

Sat, 2017-08-12 22:34

I can't seem to get webpack to compile Vue components. When I open a page that uses a component I get [Vue warn]: Failed to mount component: template or render function not defined. and in place of the component vue renders <-- function (a, b, c, d) { return createElement(vm, a, b, c, d, true); } -->

My webpack config.

module.exports = { entry: __dirname + '/display.js', output: { filename: 'bundle.js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' } ] } }

I've created a simplified project to demonstrate my problem. https://gist.github.com/RedHatter/8eadc65bd5f8327f26dcfd10a7bf3dad

Any help would be much appreciated.

Categories: Software

v-select item doesn't change value

Sat, 2017-08-12 21:45

When I make the selection nothing happens. Setting initial value works.

template:

<v-select :items="accountTypes" v-model="formData.AccountName" </v-select>

script data:

accountTypes: [ {value: 1, text: "student"}, {value: 2, text: "company"} ], formData: { FirstName: '', LastName: '', Email: '', AccountTypeId: 1, AccountName: 1, UserName: '', Password: '' },

I've looked into the source code and I found out that selectItem won't get triggered in v-select's generator line 128 (version 0.14.8, see code below)

const data = { on: { click: e => this.selectItem(item) }, props: { avatar: item === Object(item) && 'avatar' in item, ripple: true, value: active } }

I've tried upgrading and downgrading modules, but I think there is some kind of a "stupid" mistake somewhere. Thanks for any kind of input :)

Categories: Software

Reusable increment and decrement functions in Vue.js

Sat, 2017-08-12 21:35

I'm new to Vue.js and still practicing all features. I was wondering how can I write reusable functions for increment and decrement based on this code - that's what I have for now but it's repetitive. So I want to use increment/decrement function for two different buttons. Here's jsfiddle demo!

new Vue ({ el: "#pomodoro-clock", data: { breakLength: 5, sessionLength: 25, }, methods: { addBreak: function(inc){ this.breakLength += inc; }, subtractBreak: function(dec){ if(this.breakLength === 1) return; this.breakLength -= dec; }, addSession: function(inc){ this.sessionLength += inc; }, subtractSession: function(dec){ if(this.sessionLength === 1) return; this.sessionLength -= dec; } } });
Categories: Software

Vue.js mixins call parent method in overridden implementation

Sat, 2017-08-12 21:31

I'm using vuejs-datepicker component in a project however I need some custom behaviour that's why I decided to create my own datepicker and inject vuejs-datepicker as a mixin. The solution works fine but I'm looking for a way to call the parent method inside my overridden one. That's how my component looks for now:

import Datepicker from 'vuejs-datepicker' export default { props: { /** * My custom property startDate to open a calendar on the given date by default */ startDate: { validator: function (val) { return val === null || val instanceof Date || typeof val === 'string' }, default: new Date() } }, mixins: [ Datepicker ], methods: { /** * I override parent method setPageDate to read default startDate when none is specified */ setPageDate (date) { // my code to set default date from the property if (!date) { date = this.startDate } // this part is the same as in the original method this.pageDate = new Date(date.getFullYear(), date.getMonth(), 1, date.getHours(), date.getMinutes()).getTime() } } }

Just one line of copied code isn't a big deal but I expect I need to override more methods in the future. So I'm looking for the best way to call that parent method inside my implementation, something like this.parent(date) or this.super(date). Is it possible at all?

Categories: Software

Add vue.js Component from Child to Parent

Sat, 2017-08-12 21:05

Is there any way to render a vue.js component from a child component to on of its parents (maybe not the direct parent) like with slots but in the opposite direction?

My use case: In my root component I do have a <router-view> and a container for modals. from any child component of the router-view I would like to be able to add a child component to the modal wrapper.

Did I miss a feature of vue.js here or is there a even better practice to solve this problem?

Categories: Software

Vue.js + Vuetify using v-data-table within v-for

Sat, 2017-08-12 21:03

I have 2 computed arrays, homeTeam and awayTeam. The code below does work to generate 2 tables to display the homeTeam and awayTeam, how can I simplify the code to only create the table once and loop through the homeTeam and awayTeam. I tried wrapping it in a v-for with an array of ['homeTeam','awayTeam], but that did not work. The computed works, everything below works, I just want to simplify the template.

<v-flex xs12 md6> <v-data-table :headers="headers" :items="homeTeam" hide-actions class="elevation-1 white"> <template slot="items" scope="props"> <td class="text-xs-right" v-model="gamesheet.number">{{ props.item.number }}</td> <td v-model="gamesheet.name">{{ props.item.name }}</td> </template> </v-data-table> </v-flex> <v-flex xs12 md6> <v-data-table :headers="headers" :items="awayTeam" hide-actions class="elevation-1 white"> <template slot="items" scope="props"> <td class="text-xs-right" v-model="gamesheet.number">{{ props.item.number }}</td> <td v-model="gamesheet.name">{{ props.item.name }}</td> </template> </v-data-table> </v-flex> ____ computed: { homeTeam() { return this.players.filter((player) => { return player.team == this.gameinfo.home; }) }, awayTeam() { return this.players.filter((player) => { return player.team == this.gameinfo.away; }) }, spares() { return this.players.filter((player) => { return player.team != this.gameinfo.home && player.team != this.gameinfo.away; }) }, }, ____
Categories: Software

laramix with vue-masonry package error

Sat, 2017-08-12 21:01

I'm wroking on laravel 5.4 project.
The question is vue-masonry(https://github.com/shershen08/vue-masonry) package doesn't work with the following error

[Vue warn]: Failed to resolve directive: masonry [Vue warn]: Failed to resolve directive: masonry-tile

Please help me to check my setting that are the wrong part.

Here is my app.js :

require('./bootstrap'); require('masonry-layout'); require('imagesloaded'); require('fancybox'); var vueMasonry = require('vue-masonry'); Vue.use(vueMasonry);

the bootstrap.js still original without modify a word, and package.json is here:

{ "private": true, "scripts": { "dev": "npm run development", "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js", "watch-poll": "npm run watch -- --watch-poll", "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js", "prod": "npm run production", "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js" }, "devDependencies": { "bootstrap-sass": "^3.3.7", "cross-env": "^3.2.3", "laravel-mix": "0.*", "lodash": "^4.17.4", "minifier": "^0.8.1", "stylus": "^0.54.5", "stylus-loader": "^3.0.1" }, "dependencies": { "axios": "^0.15.3", "fancybox": "^3.0.0", "imagesloaded": "^4.1.3", "jquery": "^3.1.1", "masonry-layout": "^4.2.0", "swiper": "^3.4.2", "vue": "^2.1.10", "vue-masonry": "^0.10.7" } }

And the final Html is something like:

<div class="grid-wrap" v-masonry fit-width="true" transition-duration="0.3s" item-selector=".grid-item" fit-width="true" > <div v-masonry-tile class="grid-item" v-for="wall in walls"> <div class="grid-date"> @{{ wall.created_at }} </div> </div> </div>
Categories: Software

Make Vue elements draggable with jQuery UI

Sat, 2017-08-12 20:45

In my app, I make 2 ajax calls to pull in new data every 10 seconds. This data will often change. I want to make the Dom elements I create draggable.

  1. What is the best way to structure this within my apps?
  2. Is there a way to achieve this without calling $(elements).draggable() every time? There will be 1000+ DOM elements created in one of my apps.

var height = $(document).height(); var width = $(document).width(); $(function() { var app = new Vue({ el: '#main', data: { tables: [] }, methods: { loadTables() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'tables/getTables/' + event_id }).done(data => { this.tables = data; }); }, computeOffsets(table) { return { top: (table.position_x * width) + 'px', left: (table.position_y * height) + 'px' } } }, mounted() { this.loadTables(); setInterval(() => { console.log("Getting Tables"); this.loadTables(); }, 10000); } }); var sidebar = new Vue({ el: '#sidebar', data: { people: [] }, methods: { isCheckedIn(person) { return person.reg_scan == null ? true : false; }, loadPeople() { $.ajax({ method: 'POST', dataType: 'json', url: base_url + 'users/getParticipants/' + event_id }).done(data => { this.people = data; }); } }, mounted() { this.loadPeople(); setInterval(() => { console.log("Getting People"); this.loadPeople(); }, 10000); } }); }); .table { position: absolute; } #sidebar { width: 10%; float: left; height: 500px; overflow-y: scroll; } .checked-in { background-color: lightgreen; } <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> <div id="sidebar"> <div v-for="person in people" :class="{'checked-in': isCheckedIn(person), 'person' : true}" :id="person.id"> {{person.first_name + ' ' + person.last_name}} </div> </div> <div id="main"> <div class='table' v-for="table in tables" :style="computeOffsets(table)"> {{table.name}} </div> </div>

Categories: Software

vuejs start a timer for every record

Sat, 2017-08-12 18:58

I have this component rendered, I need to tell the users how much time remaining for each record displayed

I couldn't get anything worked out, I don't know any legible ways to work it out, so just trying calling out methods. I tried child components too but no avail.

<template> <div> <ul v-for="question in questions"> {{init_timer(secs)}} {{start_timer()}} <li> <a href="#" id="user-profile-text-link">{{question.name}}</a> <span class="question_clock">Validity : -- counter : {{time_remaining}} </span> </small> </li> </ul> </div> </template> <script> export default { data: function(){ return { questions: [], time_remaining : 1 }; }, methods: { init_timer: function(secs) { this.time_remaining = secs }, start_timer: function() { console.log('startiem') setTimeout(function () { this.time_remaining -= 1 }.bind(this), 1000) }, } , created: function(){ $.getJSON('/questions/json', function(response){ this.questions = response }.bind(this )); }, } </script>

any help is much appreciated

Categories: Software

Testing VueJS method inside of a promise witch is returned from a vuex action

Sat, 2017-08-12 18:38

I have a Vue component, witch is using a mapped action from a vuex store, which returns a promise. When the component calls the mapped action, and the mapped action is resolved, I am calling another vue method vm.$router.push(). I want to assert that the push method gets called. Here is my component, test, and some helper methods I created to sub out the component with vuex and vue-router.

Here is my .vue component with some console.logs to track what's going on.

<template> <div> <button @click="promise" class="click-promise">Promise</button> </div> </template> <script> import { mapActions } from 'vuex' export default { methods: { ...mapActions(['promiseAction']), promise(){ const vm = this vm.$router.push('/some/route') console.log('before promiseAction') console.log(vm.promiseAction()) return vm.promiseAction().then(function (response) { console.log('inside promiseAction') vm.$router.push('/some/other/route') }) } } } </script>

Here is my test. I'm using Mocha, Karma, Chai, and jquery-chia

import Testing from '@/components/Testing' describe('Testing.vue', () => { const mount = componentHelper(Testing) it.only('assert something in a promise returned from an action', () => { const promise = new Promise(resolve => resolve('success')) const promiseAction = stubAction('promiseAction').returns(promise) const vm = mount() const routerPush = sinon.spy(vm.$router, 'push') $('.click-promise').click() expect(promiseAction).to.have.been.called expect(routerPush).to.have.been.calledWith('/some/route') //this passes return vm.$nextTick(() => { console.log('inside nextTick') expect(routerPush).to.have.been.calledWith('/some/other/routes') //this never happens }) }) })

And here is my helpers file. I'm not sure if this is 100% neccisary, but I wanted to include everything in this post

import Vue from 'vue' import Vuex from 'vuex' import VueRouter from 'vue-router' Vue.use(Vuex) Vue.use(VueRouter) let div beforeEach(() => { // create a dom element for the component to mount to div = document.createElement('div') document.body.appendChild(div) }) afterEach(() => { // clean up the document nodes after each test Array.prototype.forEach.call(document.querySelectorAll('body *:not([type="text/javascript"])'), node => { node.parentNode.removeChild(node) }) }) // stub out a store config object const storeConfig = { actions: {} } /** * Set up a function that will attach the mock store to the component * and mount the component to the test div element * * Use like this: * const mount = componentHelper(YourComponent) * do some setup * call mount() to instantiate the mocked component * * @param component * @returns {function()} */ window.componentHelper = function (component) { const router = new VueRouter({}) return () => { // 1. attaches the stubbed store to the component component.store = new Vuex.Store(storeConfig) component.router = router // 2. mounts the component to the dom element // 3. returns the vue instance return new Vue(component).$mount(div) } } /** * Creates an action to be added to the fake store * returns a sinon stub which can be asserted against * @param actionName */ window.stubAction = (actionName) => { // 1. create a stub const stub = sinon.stub() // 2. create the action function that will be placed in the store and add it to the store storeConfig.actions[actionName] = function (context, ...args) { // 3. when this action is called it will call the stub // return the stub so you can assert against the stubbed return value // example: stubAction('fakeAction').returns('xyz') return stub(...args) } // 4. return the stub that was placed in the return of the action for assertions return stub }

When I run this test this is what I get.

LOG LOG: 'before promiseAction' LOG LOG: Promise{_c: [], _a: undefined, _s: 1, _d: true, _v: 'success', _h: 0, _n: true} Testing.vue ✓ assert something in a promise returned from an action PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 4 SUCCESS (0.045 secs / 0.018 secs) TOTAL: 1 SUCCESS =============================== Coverage summary =============================== Statements : 31.58% ( 6/19 ) Branches : 100% ( 0/0 ) Functions : 0% ( 0/2 ) Lines : 31.58% ( 6/19 ) ================================================================================ LOG LOG: 'inside nextTick' ERROR LOG: '[Vue warn]: Error in nextTick: "AssertionError: expected push to have been called with arguments /some/other/routes /some/route /some/other/routes " (found in <Root>)' ERROR LOG: AssertionError{message: 'expected push to have been called with arguments /some/other/routes /some/route /some/other/routes ', showDiff: false, actual: push, expected: undefined, stack: undefined, line: 210, sourceURL: 'http://localhost:9877/absolute/home/doug/Code/projects/vue-testing-sandbox/node_modules/chai/chai.js?ab7cf506d9d77c111c878b1e10b7f25348630760'} LOG LOG: 'inside promiseAction'

As you can see the test passes, but the code inside of the promise does not run until after the test is done. I'm talking about this section

return vm.promiseAction().then(function (response) { console.log('inside promiseAction') vm.$router.push('/some/other/route') })

I also logged out the promise function console.log(vm.promiseAction()) and you can see it is what you would expect.

How can I get the test to wait for the promise? I thought nextTick might be the answer, but it doesn't seem to be working.

Thanks for any help.

Categories: Software

Is there a way to attach an event handler to a drawer opening and closing?

Sat, 2017-08-12 17:40

I'm working on a game for my son and I would like the game to pause automatically when the drawer is opened. In order to accomplish that, I want to associate a dispatch() call to the drawer opening event.

Categories: Software

Populating table with object containing an array in vuejs?

Sat, 2017-08-12 17:03

I am trying to populate table with an object which contains an array.I am able to successfully do that but i want each task name to have its own row right now they are coming in a single row.

{level_image :"image"level_name:"1"task_name: ["game","taskgame","jenga"]}

<tr v-for="tel in result" :key="tel.level_image" :pey="tel.level_name"> <td>{{tel.level_image}}</td> <td>{{tel.level_name}}</td> <td v-for="task in tel.task_name">{{task}}</td> </tr>
Categories: Software

Download fileResult docx on client side

Sat, 2017-08-12 16:37

I am working on a client-server application, and at the moment i am returning a file result in my web api controller, like this:

FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes(docDestination), "application/msword") { FileDownloadName = "myFile.docx" }; return result;

on my client side i receive the response like this:

enter image description here

i thaught at begin that the browser detects the file automaticly and fires the download dialog, but no, so i tried to treat the result as a blob like this:

.then(response => { console.log("here lives the response:", response); var headers = response.headers; var blob = new Blob([response.bodyText], { type: headers['application/msword'] }); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "Filename"; link.click();

the download fires, but the content is not identified as docx file, and his content is broken.

Any tip on how to do it?

Thanks

Categories: Software

How to filter YouTube URL when entered in a input?

Sat, 2017-08-12 16:22

enter image description here

How do I filter a YouTube URL like above picture? when Copy paste the URL It should automatically detect the YouTube and display like above.

can the process done through Laravel or Vue.js ?

Categories: Software

Why does my vue project show this error?

Sat, 2017-08-12 16:12

Idea show me this :

Starting dev server... ERROR Failed to compile with 1 errors20:37:49

This relative module was not found:

Categories: Software

How to access this.$root from VueJS component when inside a test

Sat, 2017-08-12 15:42

In VueJS 2.4, we can access root data from component thanks to this.$root, like in this JSFiddle:

https://jsfiddle.net/bjg2yL1u/1/

If you click on a button, you can see 'orange' displayed in the console, which is a root data, not owned by the todo-item who triggered it.

Now I am inside a Jasmine test. This test works/run/is green properly.

But the console.log inside todo-item component outputs 'undefined'.

How can I inject data to this.$root instance when inside a test ?

describe("TodoItem", function() { var sut; var message = {text:'word'} beforeEach(function() { var Constructor = Vue.extend(TodoItem); sut = new Constructor({ propsData: { todo: message, } }).$mount(); }); it("Should be able to reverse the given word", function() { // Given expect(sut.todo.text).toEqual('word'); expect($(sut.$el).find('li').text()).toEqual('word'); //When sut.reverseMessage(); // Bang !! problem here. 'undefined' is printed, because there is nothing attached to this.$root when inside a test // Then expect(sut.todo.text).toEqual('drow'); }); });
Categories: Software

Laravel\Vue - Request data empty on a production server

Sat, 2017-08-12 15:16

I have a component where I am uploading a video file, everything works fine on my local machine, and it used to work fine on the production server, until only recently after I have done some work and made changes that I saw that it doesn't work now on the production server:

I am using Vue v. 1.0.28, and this is the upload component:

<template> <div class="card-content col-md-10 col-md-offset-1"> <div v-if="!uploading"> <div class="col-md-12 Image-input__input-wrapper"> Upload video <input type="file" name="video" id="video" @change="fileInputChange" class="Image-input__input" accept="video/*"> </div> </div> <div class="alert alert-danger video-upload-alert" v-if="failed">Something went wrong. Please check the video format and try again. If you need any help please contact our <a>support service.</a></div> <div id="video-form"> <div class="alert alert-info" v-if="uploading && !failed && !uploadingComplete"> Please do not navigate away from this page, until the video has finished uploading. Your video will be available at <a href="{{ $root.url }}/videos/{{ uid }}" target="_blank">{{ $root.url }}/videos/{{ uid }}</a>, once uploaded. </div> <div class="alert alert-success" v-if="uploading && !failed && uploadingComplete"> Upload complete. Video is now processing. <a href="/videos">Go to your videos</a>. </div> <div class="progress" v-if="uploading && !failed && !uploadingComplete"> <div class="progress-bar" v-bind:style="{ width: fileProgress + '%' }"></div> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="title" class="control-label">Title</label> <input type="text" class="form-control" v-model="title"> </div> <!-- <div class="col-md-12 form-group"> <label for="visibility" class="control-label">Visibility</label> <select class="form-control" v-model="visibility"> <option value="private">Private</option> <option value="unlisted">Unlisted</option> <option value="public">Public</option> </select> </div> --> </div> <div class="row"> <div class="col-md-12 form-group"> <label for="description" class="control-label">Description</label> <textarea class="form-control" v-model="description"></textarea> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <button type="submit" class="btn btn-submit" @click.prevent="update">Save</button> </div> </div> <div class="row"> <div class="col-md-12 form-group"> <span class="help-block pull-right">{{ saveStatus }}</span> </div> </div> </div> </template> <script> function initialState (){ return { uid: null, uploading: false, uploadingComplete: false, failed: false, title: null, link: null, description: null, visibility: 'private', saveStatus: null, fileProgress: 0 } } export default { data: function (){ return initialState(); }, methods: { fileInputChange() { this.uploading = true; this.failed = false; this.file = document.getElementById('video').files[0]; var isVideo = this.isVideo(this.file.name.split('.').pop()); if (isVideo) { this.store().then(() => { var form = new FormData(); form.append('video', this.file); form.append('uid', this.uid); this.$http.post('/upload', form, { progress: (e) => { if (e.lengthComputable) { this.updateProgress(e) } } }).then(() => { this.uploadingComplete = true this.uploading = false }, () => { this.failed = true this.uploading = false }); }, () => { this.failed = true this.uploading = false }) } else { this.failed = true this.uploading = false } }, isVideo(extension) { switch (extension.toLowerCase()) { case 'm4v': case 'avi': case 'mpg': case 'mp4': case 'mp3': case 'mov': case 'wmv': case 'flv': return true; } return false; }, store() { return this.$http.post('/videos', { title: this.title, description: this.description, visibility: this.visibility, extension: this.file.name.split('.').pop() }).then((response) => { this.uid = response.json().data.uid; }); }, update() { this.saveStatus = 'Saving changes.'; return this.$http.put('/videos/' + this.uid, { link: this.link, title: this.title, description: this.description, visibility: this.visibility }).then((response) => { this.saveStatus = 'Changes saved.'; setTimeout(() => { this.saveStatus = null }, 3000) }, () => { this.saveStatus = 'Failed to save changes.'; }); }, updateProgress(e) { e.percent = (e.loaded / e.total) * 100; this.fileProgress = e.percent; }, } } </script>

The problem is that on upload in my controller in the store function I am receiving empty request object on the production server, and then it fails to find the video:

class VideoUploadController extends Controller { public function index() { return view('video.upload'); } public function store(Request $request) { $player = $request->user()->player()->first(); $video = $player->videos()->where('uid', $request->uid)->firstOrFail(); $request->file('video')->move(storage_path() . '/uploads', $video->video_filename); $this->dispatch(new UploadVideo( $video->video_filename )); return response()->json(null, 200); } }

I am not sure what is going on, since like I wrote it works fine on the local machine, and there I am sending a request that looks like this:

req: {uid: "1598efd62620bd", video: {}}

What is wrong and how can I fix this?

Categories: Software

Axios interceptor doesn't intercept on page load

Sat, 2017-08-12 11:35

I am implementing JWT into my Vue application for authorization and I refresh my tokens once they are used.

I have used axios interceptors so I can intercept every request to my API backend and this seems to work on login etc... but once I refresh the page the request is made as normal using the last token.

The problem is the axios interceptors don't seem to work at this point, so once the token has been used I can't update it with the new one.

Here's how I'm setting my interceptors:-

window.axios.interceptors.request.use(function (config) { console.log("Sent request!"); return config; }, function (error) { console.log("Failed sending request!"); return Promise.reject(error); }); window.axios.interceptors.response.use(function (response) { console.log("Got headers:", response.headers); if (response.headers.hasOwnProperty('authorization')) { console.log("Got authorization:", response.headers.authorization); Store.auth.setToken(response.headers.authorization); } return response; }, function(err){ console.log("Got error", err); });

I don't get any of the console.log's on page load.

I am setting my interceptors in the root app's beforeMount method. I've tried moving them to beforeCreate and I still get the same issue.

Categories: Software

Resetting Vuex store state, properly

Sat, 2017-08-12 10:26

I have a Nuxt application with the following store / state setting:

const store = () => { return new Vuex.Store({ state: { user: { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } }, getters, actions, mutations }) }

I update the state via mutation upon login and also persist the data in localStorage and in a cookie. On Logout I'll clear localStorate and the cookies and also want to reset the state to its initial state:

import { setUser, unsetUser } from '~/utils/auth' var config = require('~/config.js').get(process.env.NODE_ENV) const actions = { nuxtServerInit ({ commit }, { req }) { // TODO }, async login ({ commit }, { payload, $axios }) { try { const { data } = await $axios.post(config.auth.LOGIN, payload) var user = _.pick(data, ['name', // etc]) user.auth.isLoggedIn = true commit('SET_USER', user) // Set the cookie setUser({ key: user.username, payload: user }) } catch (error) { if (error.response && error.response.status === 401) { throw new Error('Bad Credentials') } throw error } }, logout ({ commit }) { unsetUser() commit('CLEAR_STATE') } }

I tried different approaches resetting the state to no avail:

try #1:

CLEAR_STATE: (state) => { console.log('resetting data...') var initialState = { auth: { isLoggedIn: false }, subscription: { has_a_subscription: false }, current_check_in: {}, current_study_level: {} } state.user = Object.assign({}, state.user, initialState) }

try #2: Define functions to return the initial state(s):

CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state, 'user', initialStates.user()) }

try #3:

CLEAR_STATE: (state) => { console.log('resetting data...') Vue.set(state.user, 'auth', initialStates.auth()) Vue.set(state.user, 'subscription', initialStates.subscription()) Vue.set(state.user, 'current_check_in', initialStates.current_check_in()) Vue.set(state.user, 'current_study_level', initialStates.current_study_level()) }

The mutation 'CLEAR_STORE' doesn't get recorded in vue dev tools even though the console log 'resetting data' appears. There must be something that I am missing here.

I am using the latest 1.0 release candidate of nuxt:

"@nuxtjs/axios": "^3.1.0", "@nuxtjs/component-cache": "^0.1.3", "@nuxtjs/pwa": "latest", "backpack-core": "^0.4.1", "body-parser": "^1.17.2", "es6-promise": "^4.1.1", "express": "^4.15.3", "firebase": "^4.2.0", "js-cookie": "^2.1.4", "jwt-decode": "^2.2.0", "nuxt": "^1.0.0-rc4", "vuelidate": "^0.5.0", "vuetify": "^0.14.0", "whatwg-fetch": "^2.0.3"
Categories: Software

Pages