Vuejs

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

vue html5 editor how to get data

Thu, 2017-07-27 16:05

I tried to implement this editor in my app. But I do not know how to retrieve the data with @change in my case. (3 editors on the same page).

My code:

<script src="http://tai.coding.me/vue-html5-editor/vue-html5-editor.js"></script> <link href="https://cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/> <script src="https://cdn.bootcss.com/vue/2.2.6/vue.js"></script> <body> <div id="app"> <div v-for="content in contents" > <p> <span style="white-space: nowrap">content {{content.id}}: {{content.area}}</span> </p> <vue-html5-editor :content="content.area" :height="300" :show-module-name="showModuleName" @change="updateData(content.id)" ref="editor"></vue-html5-editor> </div> <script> Vue.use(VueHtml5Editor, { showModuleName: false, image: { sizeLimit: 512 * 1024, compress: true, width: 500, height: 500, quality: 80 } }) new Vue({ el: "#app", data: { contents: [ {id: 1,area: "<h3>vue html5 editor</h3>"}, {id: 2,area: "<h3>vue html5 editor</h3>"}, {id: 3,area: "<h3>vue html5 editor</h3>"} ], showModuleName: false, }, methods: { updateData: function (id,data) { // sync toto to component this.contents[id-1].area = data; } } }) </script> </body>

How does the first "updateData" work? How can I implement it in my code?

Categories: Software

How to add libraries vue in laravel?

Thu, 2017-07-27 15:47

I'm using laravel 5.4, with webpack and vue. I'm not sure how to add new libraries to use in vue.

For example, I run

npm install --save jquery vue2-select

What do I need to do next? I need to add:

Import Selectize from 'vue2-selectize'

or

Require ('vue2-selectize')

In the

resources / assets / js / app.js

file or

resources / assets / js / bootstrap.js

?

Can someone help me with the correct order to work?

Thank you!

Categories: Software

Dynamically render custom Vue component from json schema and bind v-model to another json schema

Thu, 2017-07-27 15:47

Here is how i use my custom components in my html

<custom-input v-model="person.name" :title="'Person Name'"> </custom-input> <custom-select v-model="person.country" :options="countryList" :title="'Country'"> </custom-select>

What i want is to generate these 2 components with all the attributes using json schema and bind the v-model to another json schema. So i can iterate the json array which defines what component tag is what attributes it should have etc etc. and then bind the v-model to a data schema from the second json schema. I'm thinking about a proxyComponent that renders them but it will become too complicated since some components dont have v-model, instead they have @input event listener for their value

Json model data:

{ person: { name: '', country: '', }, }

Json schema which defines the components

[ { tag: 'custom-input', attributes: { vModel: 'person.name', title: 'Person Name', }, }, { tag: 'custom-select', attributes: { vModel: 'person.country', options: 'countryList', title: 'Country', }, }, ]
Categories: Software

What is a proper way to deal with Vue.js props that from the response of backend

Thu, 2017-07-27 15:38

I am wondering that what is a proper way to deal with props in Vue.js if the prop is from the response of backend?

Ok, let's say the child component has a prop called person. a name is in person object.

<template> {{ person.name }} <template> <script> export default { name: 'ChildComponent', props:['person'], created(){ this.getName(); }, data(){return{name:''}}, methods:{ getName(){ this.name = this.person.name; } } </script>

The parent component is like this

<template> <ChildComponent :person="person"></ChildComponent> <template> <script> export default { name: 'ParentComponent', created(){ this.getPerson(); } data(){ return { person: null } }, methods:{getPerson(){ // send request to server or api then update name sendrequest().then(person => { this.person = person}); }} </script>

At first, before the get the response, there will be a warning can't get name from person. I know 2 methods to handle this:

  1. <ChildComponent :person="person" v-if="person"></ChildComponent>
  2. watch person prop in, every time the person is changed, rerun the getName() method in childcomponent or set name as a computed attribute.

So here is the question again, are they the proper way to handle this? Is there still some other methods like using Vuex?

Thx

Categories: Software

How to access data variables in vuejs within a single file component

Thu, 2017-07-27 14:51

I am attempting to read a variable from within the data object of a Vue component.

This is the Vue template I'm using

<template> <section> <b-field label="Username"> <b-input v-model="username"></b-input> </b-field> <b-field label="Password"> <b-input type="password" password-reveal v-model="password"></b-input> </b-field> <b-field label="Engineer number"> <b-input type="number" v-model="engineer"></b-input> </b-field> <a class="button" @click="send_login">Login</a> </section> </template> <script> import {socket} from './../../main.js' export default { data() { return { username: '', password: '', engineer: '', } }, methods: { send_login: () => { console.log(this.engineer) } } } </script>

this.engineer always print undefined.

If I wasn't using the template files then this works

let login = new Vue({ el: '#loginApp', data: { username: '', password: '', engineer: '', }, methods: { login: () => { console.log(login.engineer); }, }, });

Any ideas on what I'm doing wrong?

Categories: Software

code splitting vuex application

Thu, 2017-07-27 14:44

I have a vuex store and i'd like to apply code splitting on it.

Following this tutorial I tried this:

import Vuex from 'vuex' import Vue from 'vue' import createLogger from 'vuex/dist/logger' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' const store = new Vuex.Store({ strict: debug, plugins: debug ? [createLogger] : [], state: { loading: false }, mutations: { toggleLoading: (state) => { state.loading = !state.loading } }, getters: { loading: state => state.loading }, actions: { toggleLoading: ({commit}) => { commit('toggleLoading') } } }) import('./modules/userModule').then(userModule => { store.registerModule('user', userModule) }) import('./modules/tenantsModule').then(tenantsModule => { store.registerModule('tenants', tenantsModule) }) import('./modules/updatesModule').then(updatesModule => { store.registerModule('updates', updatesModule) }) export default store

But the application fails :

webpack-internal:///24:739 [vuex] unknown getter: user

What am i doing wrong?

Categories: Software

Unable to access `get` method in vue-resource

Thu, 2017-07-27 14:23

I have a tiny vue app where I'm wanting to use vue-resource to request an api endpoint.

  1. I've installed vue-resource via npm
  2. I've added the Vue.use(VueResource) lines to my bootstrap file
  3. I've setup my component like this to call the .get method

Blog.vue

... mounted () { this.fetchPosts() }, methods: { fetchPosts: () => { debugger; this.$http.get('my-url') .then(response => { console.log(response) }) } } ...

I've seen a few github issues and SO posts which touch on this type of problem but most seem to relate to incorrect configuration which I don't think I have (happy to be proven wrong!)

The specific console error I get is:

Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

What's odd about this is that if you see my debugger line, if I console.log this.$http.get at that point I get:

function (url, options$$1) { return this(assign(options$$1 || {}, {url: url, method: method$$1})); }

If I let the code run and then attempt the console.log afterwards I get:

Cannot read property 'get' of undefined

As a result I presume it's some kind of this context issue, but from what I can see the reference should be correct...shouldn't it?

Categories: Software

Vuex interlocking state with another

Thu, 2017-07-27 14:14

My state is inter-dependent with another, something like this: https://jsfiddle.net/MagicMagnate/1zufrspx/

const store = new Vuex.Store({ state: { checkedNames: ['Jack', 'Mike'], interlockedState : 'foo' }, mutations: { updateChecked(state, payload) { state.checkedNames = payload state.interlockedState = 'bar' //trying to set the state but failed } }, actions: { updateChecked({ commit }, payload) { commit('updateChecked', payload) } } }) new Vue({ store, el: '#example', //data: {interlockedState:'foo'}, computed: { checkedNames: { get() { return this.$store.state.checkedNames }, set(str) { this.$store.dispatch('updateChecked', str) } } } })

Only more complex with case and if else, I know I shouldn't mutate directly from state directly, but I'm running out idea on how to assign a new value to state to mutate so those two states aren't interlocked with each other.

Categories: Software

Issue with babel loader + UglifyJS

Thu, 2017-07-27 13:56

I'm having some issues using the babel-loader plugin in conjunction with uglifyJS. I'm no expert here, but it seems like my ES6 is not being transpiled to es5 correctly.

Contents of my webpack.production.js file:

var path = require("path"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var extractSass = new ExtractTextPlugin({ filename: "[name].[contenthash].css", disable: true }); var webpack = require("webpack"); module.exports = { entry: ['babel-polyfill', './assets/js/app.js'], output: { path: path.resolve(__dirname, "dist"), //publicPath: "/assets/", filename: 'bundle.js' }, //devtool:'source-map', module : { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['es2015'] } } ], rules: [ { test: /\.html/, use: [{ loader: "html-loader" }] }, { test: /\.scss$/, loader: extractSass.extract({ use: [{ loader: "css-loader", options: { sourceMap : true} }, { loader: "sass-loader", options: { sourceMap : true} }], // use style-loader in development fallback: "style-loader" }) } ] }, resolve: { mainFields: ['browserify', 'browser', 'module', 'main'] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), extractSass, new webpack.optimize.UglifyJsPlugin({minimize: true}) ] };

My package.json:

{ "name": "mobiile-app-template", "version": "1.0.0", "description": "A single page app template", "main": "app.js", "scripts": { "babel": "babel --presets es2015 js/main.js -o build/main.bundle.js", "dev": "webpack-dev-server --inline --hot --host=127.0.0.1", "build": "cross-env NODE_ENV=production webpack --progress --hide-modules --config webpack.production.config.js", "predeploy": "npm run build", "deploy": "surge --project . --domain skyy-ba.surge.sh" }, "dependencies": { "axios": "^0.16.2", "babel-polyfill": "^6.23.0", "babel-runtime": "^6.23.0", "html-loader": "^0.4.4", "jwt-decode": "^2.2.0", "vee-validate": "^2.0.0-rc.5", "vue": "^2.1.3", "vue-carousel": "^0.6.4", "vue-router": "^2.5.3", "vue-simple-spinner": "^1.2.1", "vue-simple-upload": "^0.1.6", "vue-spinner": "^1.0.2", "vuex": "^2.3.1" }, "author": "", "license": "ISC", "devDependencies": { "babel-core": "^6.24.1", "babel-loader": "^7.0.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-es2015": "^6.24.1", "copy-webpack-plugin": "^4.0.1", "cross-env": "^1.0.6", "css-loader": "^0.26.4", "extract-text-webpack-plugin": "^2.1.0", "node-sass": "^4.5.0", "sass-loader": "^6.0.3", "style-loader": "^0.13.2", "surge": "^0.18.0", "webpack": "^2.5.1", "webpack-dev-server": "^2.4.1" } }

Anyone have any ideas? Tried so many different solutions with no luck so far :-(

Categories: Software

How to change the resize step in the Vuetify grid system

Thu, 2017-07-27 13:54

I have been working with Vue.js and Vuetify recently and I am now trying to implement a mobile first app.

In this SPA, I display a list of items. I would like these items to be displayed in a grid when the screen is wide enough and as a regular list when the screen is smaller.

For that, I followed the example here.

#example-5 { color: #fff; text-align: center; } #example-5 .card { margin-bottom: 16px; } <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet" type="text/css"> <script src="https://unpkg.com/vue/dist/vue.js"></script> <link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet" type="text/css"> <script src="https://unpkg.com/vuetify/dist/vuetify.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.common.js"></script> <div id="example-5"> <v-layout row-md column child-flex-md> <v-card dark class="primary ma-1"> <v-card-text>one</v-card-text> </v-card> <v-card dark class="secondary ma-1"> <v-card-text>two</v-card-text> </v-card> <v-card dark class="accent ma-1"> <v-card-text>three</v-card-text> </v-card> </v-layout> </div>

While this has the intended effect, I noticed that it changes between one item or three items. There is in "in between" where there are two items on the first row and only one item on the last row.

Do you have any tips on how to achieve this effect?

Is there a way in the Vuetify grid system to change the resize step to be in increments of one addition item per row instead of the current behaviour?

Thanks for your help!

Categories: Software

Vue 2 - Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810) error

Thu, 2017-07-27 13:41

I am getting the error from the title:

Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810)

Made standard setup with vue-cli (simple webpack), and this is my component:

<template> <div class="column is-4"> <nav class="panel"> <p class="panel-heading"> Authors in our library </p> <div class="panel-block"> <p class="control has-icons-left"> <input class="input is-small" type="text" placeholder="Search" v-model="search" @keyup="filterAuthors"> <span class="icon is-small is-left"> <i class="fa fa-search"></i> </span> </p> </div> <a class="panel-block is-active" v-for="author in filterAuthors"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> {{ author }} </a> </nav> </div> </template> <script> export default { data () { return { 'search' : '' } }, computed: { filterAuthors() { let search = this.search.toLowerCase(); return this.$store.state.authors.filter((author) => { return author.toLowerCase().indexOf(search) >= 0; }) } } } </script>

Strange part is that the filter is working, but every time I type into the input field, I get this error. Anyone have any idea what can it be?

Categories: Software

How to watch for Vue instance property inside component?

Thu, 2017-07-27 13:01

I have a plugin that adds some property to Vue instance.
Then I can access this property inside components using this.$plugin.prop. How can I watch for its changes? I need to do something inside component based on this.$plugin.prop value but neither watch or this.$watch worked for me. I assume its because watch works in component context so I can't watch for variable outside component, for example

mounted() { this.$watch('$plugin.prop', val => console.log(val)); }

doesn't work.
What is the right way to accomplish this?

Categories: Software

Changing a vuex state from a different component?

Thu, 2017-07-27 12:02

I have a component (modal) which relies on a store. The store has the state of the modal component - whether it is active or not.

I need to be able to call this modal to open from other components or even just on a standard link. It opens by adding an .active class.

How can I change the state of the store - either by calling the stores action or calling the modal components method (which is mapped to the store).

Modal Store:

class ModalModule { constructor() { return { namespaced: true, state: { active: false, }, mutations: { toggleActive: (state) => { return state.active = ! state.active; }, }, actions: { toggleActive({ commit }) { commit('toggleActive'); }, }, getters: { active: state => { return state.active; } } }; } } export default ModalModule;

Vue Component:

<template> <div class="modal" v-bind:class="{ active: active }"> <div class="modal-inner"> <h1>modal content here</h1> </div> <div class="modal-close" v-on:click="this.toggleActive"> X </div> </div> </template> <script> import { mapGetters, mapActions } from 'vuex'; export default { computed: { ...mapGetters('Modal', [ 'active', ]) }, methods: { ...mapActions('Modal', [ 'toggleActive', ]), } } </script>

And somewhere else I want to be able to have something like:

<button v-on:click="how to change the state??">OPEN MODAL</button>
Categories: Software

vuejs: the correct path of local json file for axios get request

Thu, 2017-07-27 11:47

In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:

My_project build config data service_general_info.json node_modules src components component-A component-A.vue

as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.

And I want to read in the data by axios library in an event handling function inside the component of component-A as following:

methods: { addData() { console.log('add json data...'); axios.get('./../../data/service_general_info.json'); }, },

I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.

The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)

Categories: Software

ES6 Functions Syntax?

Thu, 2017-07-27 10:50

I'm trying to call my namespaced store:

methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); }

Which results in the error:

Uncaught TypeError: Cannot read property 'toggleActive' of undefined

Doing the following works:

close: function() { this.toggleActive(); }

How can I use ES6 function syntax with vue/vuex?

Categories: Software

Publishing a Vuejs component as a package on npm

Thu, 2017-07-27 10:33

I created a vuejs2 project (using webpack) with 2 components, I want to publish this project on npm as a package so that I can use all the components inside this project with multiple projects (reusable components).

I published the project on npm npm publish and installed the package using npm install my-components, I found the project inside node_modules but it was with the whole source code, as if I copy/pasted the project there.

Also when I try to run npm build dist I am getting an error:

npm ERR! Darwin 16.6.0

npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "dist"

npm ERR! node v6.9.2

npm ERR! npm v3.10.9

npm ERR! missing script: dist

npm ERR! npm ERR! If you need help, you may report this error at: npm ERR!
https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request: npm ERR!
/Users/myuser/Documents/Projects/my-components/npm-debug.log

Inside my project (https://github.com/Trelllis/my-components), there is a component called vue-version which I can't use and the project my-components isn't resolved.

How can I publish this project properly with all its components?

Thanks

Categories: Software

Vue.js / vuedraggable : Adding "v-model" to a draggable makes it not draggable

Thu, 2017-07-27 10:24

I have a problem using Vue.js and the library VueDraggable (https://github.com/SortableJS/Vue.Draggable) Here is a sample of code :

<draggable v-if="n === 2 && track.getDisplayArray()[1].length !==0" element="ul" :options="{group:'layers '+ track.itemId}" v-bind:class="{ hidden: !track.show, 'child-container': track.show }" v-model="track.getDisplayArray()[1]" :move="onMove" @start="onStart" @end="onFinished"> <li class="item" v-bind:class="{ hidden: !layer.show, child: layer.show }" v-for="layer in track.getDisplayArray()[1]"> <span>{{layer.name}}</span> <img class="item-view" src="static/img/ic_view.svg" alt="view"> </li> </draggable>

onMove function just returns true, onStart and onFinished are empty (but I want to do something with them in the future ;) )

When the "v-model" property is here, the li tags which are created cannot be swapped.

When I remove this property, the li tags can be swapped.

Do you see the problem? Are they some "conflicts" between some properties that I am not aware of?

Categories: Software

How to use On input using VueJs and Laravel 5

Thu, 2017-07-27 09:52

I followed along this tutorial and it worked perfectly fine. But what I want is to not use submit button to check or perform the validation, what I want is while I'm typing, it is now validating the form. Please see my code below, or visit the link that I mentioned above.

Code:

routes

<?php Route::get('/', function () { return view('welcome'); }); Route::get('/article/create', 'ArticleController@showArticleCreationForm'); Route::post('/article', 'ArticleController@publish');



ArticleController

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class ArticleController extends Controller { public function showArticleCreationForm(){ return view('article.create'); } public function publish(Request $request){ $this->validate($request, [ 'title' => 'required|min:3', 'body' => 'required|min:10' ]); if ($request->ajax()) return; return 'publish'; } }



create.blade.php

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Create Article</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw==" crossorigin="anonymous"> <style> .body { height: 200px !important; } .error { color: darkred; margin-top: 5px; display: block; } </style> </head> <body id="app"> <form @submit.prevent="submitForm" class="col-md-4 col-md-offset-4" action="{{ URL::to('/') }}/article" method="post"> <h1>Create New Article</h1> <hr> {!! csrf_field() !!} <div class="form-group"> <input class="form-control title" type="text" name="title" placeholder="Title" v-model="formInputs.title"> <span v-if="formErrors['title']" class="error">@{{ formErrors['title'] }}</span> </div> <div class="form-group"> <textarea class="form-control body" name="body" placeholder="Content" v-model="formInputs.body"></textarea> <span v-if="formErrors['body']" class="error">@{{ formErrors['body'] }}</span> </div> <button class="btn btn-primary" type="submit">Publish</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.14/vue.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.6.1/vue-resource.min.js"></script> <script> new Vue({ el: '#app', data: { formInputs: {}, formErrors: {} }, methods: { submitForm: function(e){ var form = e.target; var action = form.action; var csrfToken = form.querySelector('input[name="_token"]').value; this.$http.post(action, this.formInputs, { headers: { 'X-CSRF-TOKEN': csrfToken } }) .then(function() { form.submit(); }) .catch(function (data, status, request) { var errors = data.data; this.formErrors = errors; }); } } }); </script> </body> </html>
Categories: Software

How to deal with 'require' of files bloating up my javascript with Webpack?

Thu, 2017-07-27 09:45

I am using Webpack to pull in .svg files which I can inline and use inside my Javascript components. It looks something like this:

export default class Svg { constructor() { const icons = require.context('public/images/svg', true, /\.svg$/); } }

It works perfectly fine. Looking at the buildfile from Webpack I can see that all of these .svg files are being put inside of my main app.js javascript file.

This bloats up my Javascript file that every user on the website needs to load. Although this is only a one time load it does add up to the initial load when someone has not cached the file yet, or when it is refreshed because of changes.

I know that only at buildtime the javascript has access to the filesystem through node.js and therefore there is probably no way around this.

How do I combat the bloat of this file thouhg?

To my knowledge there are a couple of options:

  • Use XHR request to retrieve the data. This might be slow and cause flashes of icons that are not loaded in time. This might be do-able if you were to have something fast like elasticsearch but otherwise probably not feasible.

  • Put all my .svg files into a separate file with Webpack so they will be cached longer because this files gets touched way less often than the main javascript code.

  • Use code splitting to split up my .svg. files and put each.svg` file into a module of its own. Then let webpack deal with it by injecting the modules asynchronously when needed.

The last approach would probably only be helpful for components and javascript code that is not directly visible since there will be loadtime?

Because not all .svg files are necessary the first step would be to remove the require.context and import only files that are needed.

Any thoughts on how to deal with this? Would love to hear from someone who might have some experience on this. Otherwise any and all suggestions are welcome as well. :)

Categories: Software

Laravel Echo not receiving notification from pusher

Thu, 2017-07-27 09:24

I followed up some tutorials about echo and pusher. I configured all the project as necessary but object notifications not appear at browser. I uncoment the line

App\Providers\BroadcastServiceProvider::class,

The next files it's about what I'm using:

bootstrap.js

bootstrap.js

channels.php

Broadcast channel

PackageNotifications (class which I create the notifications) enter image description here

Line which I create a new notification

enter image description here

broadcasting.php

broadcasting.php

.env

.env

I created and registered a component in vuejs called notifications then I set it out what says in laravel notifications as you can see bellow.

enter image description here

Everything is connecting with Pusher but when I send any notification it appear at pusher but as mentioned at before, the object notification is not appearing.

view

Someone have some idea about what is happening? Thanks in advance

Categories: Software

Pages