Vuejs

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

Practical use of VueJS with Laravel

Tue, 2017-08-22 16:10

I'm starting a new large-scale application and after hearing a lot about VueJS + Laravel combination i thought of using it. I followed Laracasts' Learn Vue 2: Step By Step series and some tutorials to understand how it works.

But have few questions in mind:

  1. Why do we even need to use Vue with Laravel. I understand that we can create component like <user-profile></user-profile> in Vue, and then use it in Laravel Blade. But it looks like over-complication things? Firstly we pass data from controller to blade, and then further pass it to vue. Why do we need to do that?

  2. Laravel and Vue both have their own routing system. Which one to use?

Categories: Software

How to toggle class inside a loop of items in vue.js

Tue, 2017-08-22 15:55

I'm new to vue.js and have this list of items:

<div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvote"><i class="fa fa-arrow-up grey"></i></button> <div>

I want to toggle the grey to green when the upvote button is clicked.

in the methods I have:

methods: { upvote: function(joke) { joke.upvotes ++; //how to toggle grey to green here? } }

How can I achieve this? I have tried different tricks but all the tutorials change the class ALL of the items, not the one up-voted.

Categories: Software

How to retrieve images dynamically from server in Vuejs

Tue, 2017-08-22 15:45
<img class="img-responsive" :src="'http://10.20.10.161:8000/content_images/'+video.image" >

In place of http://10.20.10.161:8000 I need some predefined variable as base url of my server application.

How can I set that?

Categories: Software

Jquery: Scroll not working [duplicate]

Tue, 2017-08-22 15:05

This question already has an answer here:

I have this code:

<div class="container citiestop"> <div class="columns"> <a href="/{{$locale}}/contact#bcn" class="column is-4 citytop city-1-top red click-preloader" > <div id="tobcn">Barcelona.</div> </a> <a href="/{{$locale}}/contact#mad" class="column is-4 citytop city-2-top green click-preloader"> <div id="tomadrid">Madrid.</div> </a> <a href="/{{$locale}}/contact#mex" class="column is-4 citytop city-3-top blue click-preloader"> <div>@include('includes.trans',['es'=>'México', 'en'=>'Mexico']).</div> </a> </div> </div>

And in the bottom on the page I have 3 divs with ids: bcn, mad and mex.

I'm trying to do this with jQuery:

$('#tobcn').click = function () { $(document).scrollTo('#bcn'); }

When I click go to the URL of href but doesn't scroll.

What's wrong with the code? No error appears.

Thanks a lot, and if you need more information feel free to ask for it.

Categories: Software

Webpack not extracting CSS into files from vendor vue components

Tue, 2017-08-22 15:02

I have a problem with webpack not extracting CSS from vendor VUE components.

Html head looks like this

Vendor CSS is inserted as style tag after JS load at bottom.

Other styles in mine vue components, mine less files, styles from non-vue vendor packages are correctly splitted into main.css and vendor.css

Webpack config in Gist: https://gist.github.com/PanzerMarduk/50b66aba41364504570d9fe23b4f1535

What is missing from config ?

Thanx

Categories: Software

Vue.js: Failed to generate render function

Tue, 2017-08-22 13:58

I try to run a simple Vue.js, but I constantly receive the following error:

[Vue warn]: It seems you are using the standalone build of Vue.js in an environment with Content Security Policy that prohibits unsafe-eval. The template compiler cannot work in this environment. Consider relaxing the policy to allow unsafe-eval or pre-compiling your templates into render functions.

main.js:3180 [Vue warn]: Failed to generate render function: EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'". in

with(this){return _c('div',{attrs:{"id":"app"}})}

(found in )

Yet, I can't understand what is causing this error. I don't seem to use any dynamic templates and everything should be pre-compiled. Here is the code of my application:

import Vue from 'vue' import VueRouter from 'vue-router' const Home = Vue.component('home-component', { render() { return <div> <router-link to="/users">Users</router-link> <router-link to="/about">About</router-link> </div> } }) const Users = Vue.component('users-component', { render() { return <p>Users</p> } }) const NotFound = Vue.component('not-found-component', { render() { return <p>Not Found</p> } }) const routes = [ { path: '/', component: Home }, { path: '/users', component: Users } ] const router = new VueRouter({ routes }) const app = new Vue({ router }).$mount('#app')

And here is how I process JavaScript files in my gulpfile:

const paths = { main: 'web/javascript/src/main.js', allJs: 'web/javascript/**/*.{js,vue}', resultJs: 'public/assets/javascript/main.js', }; gulp.task('scripts', function() { return browserify(paths.main) .transform(babelify, { presets: ['es2015'], plugins: ["transform-runtime"] }) .transform(vueify) .bundle() .pipe(fs.createWriteStream(paths.resultJs)) }

There are seem to be many similar questions on StackOverflow, but none of them helped me.

Categories: Software

Webpack not creating css and js files

Tue, 2017-08-22 13:08

I am using laravel and vue.js. When I do npm run dev my sass files are not compiling and they are not exist in /public. What can be the reason? I can not show code because of nda..

Categories: Software

How to filter two data set from one selection in VueJs

Tue, 2017-08-22 12:43

I'm building a small application in VueJs 2.0 where I'm having two select options with Select2 plugin as such:

<div class="form-group"><label class="col-sm-2 control-label">Categories:</label> <div class="col-sm-4"> <v-select multiple :options="selectTable" placeholder="Categories" v-model="categories"></v-select> </div> </div> <div class="hr-line-dashed"></div> <div class="form-group"><label class="col-sm-2 control-label">Sub-Categories:</label> <div class="col-sm-4"> <v-select multiple :options="selectSubtractedTable" placeholder="Subtracted Categories" v-model="subtractedCategories"></v-select> </div> </div>

Now I've a computed property to list these elements inside, like:

computed: { selectTable() { if(this.model) { return this.model.map(a => ({ value: a.id, label: a.name })); } }, selectSubtractedTable() { if(this.subModel) { return this.subModel.map(a => ({ value: a.id, label: a.name })); } } },

Now I'm having a watch function which checks the first list and remove the elements from the second list as:

watch: { categories(newValue) { this.subModel = this.model for(var i = 0; i<newValue.length; i++ ) { const element = this.subModel.find(a => a.id == newValue[i].value) console.log(element) if(element>0) this.subModel.splice(index, 1) } } }

I've data set in following format:

this.model = this.subModel = [ { "id":1,"name":"Jeans","created_at":null,"updated_at":null }, { "id":2,"name":"Shirts","created_at":null,"updated_at":null }, { "id":3,"name":"Top","created_at":null,"updated_at":null }, { "id":4,"name":"Women","created_at":null,"updated_at":null }, { "id":5,"name":"Men","created_at":null,"updated_at":null }, { "id":6,"name":"Jwellary","created_at":null,"updated_at":null } ]

and const element = this.subModel.find(a => a.id == newValue[i].value) this is always showing value 0 in the watch property

Help me out.

Categories: Software

Why can't this component access its props data?

Tue, 2017-08-22 12:20

When the following component was inline, it was able to access rowData but as a referenced template it can't:

HTML: <div id="app"> <div> <row-component v-for="(row, index) in rows" :row-data="row" v-on:delete-row="deleteThisRow(index)"></row-component> </div> </div> <script id="theRow" type="x-template"> row component: {{rowData}} <button @click="$emit('delete-row')">Delete3</button> </script> JavaScript: Vue.component('row-component', { props: ["rowData"], template: '#theRow' }) new Vue({ el: '#app', data: { rows: ["line1", "line2", "line3", "line4", "line5"] }, methods: { deleteThisRow: function(index) { this.rows.splice(index, 1); } } })

How can I get the component to recognize rowData?

https://jsfiddle.net/edwardtanguay/k1tx3z1n/

Categories: Software

How to use calendar in javascript

Tue, 2017-08-22 12:08

I'm using javascript (vue js) and I'm trying to add a calendar that I can choose from it date and time, I'm using this one:

<span class="glyphicon glyphicon-calendar"></span>

but I can only choose date from the calendar,

I want something like the Enabled/Disabled Dates Bootstrap 3 Datepicker v4 Docs, which is this one:

<div class="container"> <div class="row"> <div class='col-sm-6'> <div class="form-group"> <div class='input-group date' id='datetimepicker5'> <input type='text' class="form-control" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker5').datetimepicker({ defaultDate: "11/1/2013", disabledDates: [ moment("12/25/2013"), new Date(2013, 11 - 1, 21), "11/22/2013 00:53" ] }); }); </script> </div>

But I can't use it since it uses jQuery and I don't want something with jQuery. Is it possible?

Thank you.

Categories: Software

How to set a component non-reactive data in Vue 2?

Tue, 2017-08-22 11:57

I have a categories array, which is loaded once (in created hook) and then it is static all the time. I render this array values in a component template.

<template> <ul> <li v-for="item in myArray">{{ item }}</li> </ul> </template>

My data property looks (it does not include myArray - I dont want reactive binding):

data() { return { someReactiveData: [1, 2, 3] }; }

My create hook:

created() { // ... this.myArray = ["value 1", "value 2"]; // ... }

Problem is, that Vue throw error - I cant use myArray in a template, because this variable is not created when the DOM is created - mounted.

So how to do this? Or where can be stored component constants?

Categories: Software

Difference between the created and mounted events

Tue, 2017-08-22 11:07

Vue.js documentation describes the created and mounted events as follows:

created

Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.

mounted

Called after the instance has just been mounted where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

This hook is not called during server-side rendering.

I understand the theory, but I have 2 questions regarding practice:

  1. Is there any case where created would be used over mounted?
  2. What can I use the created event for, in real-life (real-code) situation?
Categories: Software

IE11 + Vue-Cli + Webpack + Babel - SCRIPT1003 Error

Tue, 2017-08-22 10:26

I have the SCRIPT1003: Expected ‘:’ error in IE11. I have installed vuejs over vue-cli tool. It worked until I have added vuex library to the package.json. My package.json dependencies are following:

"dependencies": { "axios": "^0.16.2", "babel-polyfill": "^6.26.0", "lodash": "^4.17.4", "rxjs": "^5.4.2", "vue": "^2.3.3", "vue-i18n": "^7.1.0", "vue-router": "^2.6.0", "vue-rx": "^3.3.0", "vuetify": "^0.14.11", "vuex": "^2.3.1", "vuex-persistedstate": "^2.0.0" }

As suggested on many other help forums I have tried using babel polyfill. My .babelrc file is like so:

{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] } }], "stage-2" ], "plugins": ["transform-runtime"], "env": { "test": { "presets": ["env", "stage-2"], "plugins": ["istanbul"] } } }

I have included the polyfill in the entry point in build/webpack.base.conf.js:

entry: { app: ['babel-polyfill', './src/main.js'] },

Unfortunately I am still getting the same error after all of this. Could you please help me how to make it work in IE11?

Thank you in advance.

Best regards,

Goran

Categories: Software

how to use vue to complete this function? [on hold]

Tue, 2017-08-22 10:19

enter image description here

I want use Vue to complete this function, when I click the buttons, input will show the result,and can mutiple,clicked button will highlighted

Categories: Software

JSON.parse() can not turn string to object, and print out SyntaxError: Unexpected token o in JSON

Tue, 2017-08-22 10:00

In my vue.js project, i use axios library to get a JSON data, and successful(1.ok could print json data: {...}). but when i use JSON.parse() method to turn data to a object, console print out a error(2.error), could you tell why?

axios.get('/data/cart.json') .then(response=> { // 1.ok console.log(response.data); // 2.error let data = JSON.parse(response.data); console.log(data); }) .catch(function(error){ console.log(error); });

This is console print out:

SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at axios.get.then.response (cart.js:19) at <anonymous>
Categories: Software

laravel vue.js - using items from node modules folder

Tue, 2017-08-22 09:37

I just installed easy-autocomplete library using npm install easy-autocomplete. Now I would use this in my .vue components. Since I am green in laravel and vue.js I don't know how to import it to use. Could I ask for your help?

Categories: Software

File to import not found

Tue, 2017-08-22 07:48

So I'm trying to import my SCSS file with all vars and mixins definitions to all components I have. File name for defs is _defs.scss:

@import "styles/defs";

I also used alias in webpack to define where to look for styles folder:

resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js', assets: path.resolve(__dirname, "src/assets/"), styles: path.resolve(__dirname, "src/styles/") } }

But for some reason webpack still throws error telling he can't find the import file.

Where am I wrong?

Categories: Software

Computed properties on function instances

Tue, 2017-08-22 07:41

In knockout.js I was able to do the following:

function Person() { this.firstName = ko.observable('Foo') this.lastName = ko.observable('Bar') this.fullName = ko.pureComputed(() => { return this.firstName() + this.lastName() }) } var p = new Person() console.log(p.fullName()) // FooBar

Is there any way to add reactive computed properties on objects which are not a component data in Vue?

Categories: Software

Checkbox selection through number of counts in array in VueJs/Javascript

Tue, 2017-08-22 07:35

I'm building a small application in Vuejs where I'm having a list of year presented in a table something like this:

<tr v-for="model in yearsTable"> <td class="text-left"> <div class="i-checks"> <label> <input type="checkbox" :value="model.id" :checked="model.active" @click="yearCheck(model)"> <i></i>{{ model.name }}</label> </div> </td> </tr>

and a computed property to have the data something like this:

computed: { yearsTable: function () { if(this.yearModel) { return this.yearModel.map(d=> ({name: d.name, id: d.id, active: d.is_active ? true : false})) } } }

I've a function in which I want to check the is_active count and I want to have only 3 to be checked at a time. I mean if more than 3 is checked then it should alert so I have a method function something like this:

yearCheck(model) { var count = 0; var ele = this.yearModel.findIndex(t => t === model) if(ele.is_active = 0) { ele.is_active = 1 } else { ele.is_active = 0 } for(var j=0; j<this.yearModel.length; j++) { if(this.yearModel[j].is_active === 1) { count++; } } if(count>3) { ele.is_active = 0 alert('You already have 3 selected years') } else { //Do other function } }

I'm getting an error of:

Uncaught TypeError: Cannot create property 'is_active' on number '-1'

Categories: Software

Cannot clear radio button Vue js

Tue, 2017-08-22 06:10

I have this three components - main, question, and questionOption. What I want is to clear the checked radio button on the questionOption from the main component startNewGame method. When I'am only using Main component resetting the radio button is just simple. I just assign the model to an empty array. Can someone help me on this. By the way, Im using onsen ui for the customize tags ans removed some unnecessary methods and data. Here is my code.

Main.vue

<div class="quiz-background"> <question v-for="(question, $indexParent) in randomQuestions" :question="question['doc'].question" :choices="question['doc']['choices']" :indexParent="$indexParent" :correctAnswer="question['doc'].correctAnswer" @collectedAnswer="pushToAnswers" > </question> <section style="margin:16px"> <v-ons-button modifier="cta" @click="submit" v-show="!isDone" >Submit </v-ons-button> </section> </div> <script> export default { data() { return { dialogVisible: false, resultDialogVisible: false, questionnaires: [], chosenAnswers: [], correct: [], total: 0, isDone: false } }, methods: { pushToAnswers(answer) { this.chosenAnswers.push(answer); }, submit() { //will compare chosenAnswers to correct answer } }, startNewGame() { //will reset answered questions this.getQuestionaire(); this.chosenAnswers = []; this.resultDialogVisible = false; this.total = 0; this.isDone = false; }, components: { Question } } </script>

Question.vue

<question-option v-for="(choice, key, $index) in choices" :choice="choice" :indexParent="indexParent" :index="$index" :letter="key" :name="'question-' + indexParent" v-model="selectedValue" @change="changeValue" > </question-option> <script> import QuestionOption from './QuestionOption.vue'; export default { data() { return { selectedValue: '' } }, props: ['question', 'indexParent', 'choices', 'chosenAnswer'], methods: { changeValue(newValue) { this.selectedValue = newValue; this.$emit('collectedAnswer', this.selectedValue); } }, components: { QuestionOption } }

Question.vue

<v-ons-list-item :modifier="longdivider" :key="letter" tappable > <label class="left"> <v-ons-radio :name="name" :input-id="indexParent + '-' + index" v-model="chosenAnswer" > </v-ons-radio> </label> <label class="center" :for="indexParent + '-' + index" > {{ letter }} . {{ choice }} </label> </v-ons-list-item> <script> export default { props: ['choice', 'indexParent', 'index', 'name', 'letter'], computed: { chosenAnswer: { get() { return this.letter; }, set() { this.$emit('change', this.letter); } } } } </script>
Categories: Software

Pages