Software
Component method response object data binding
I am starting to lose my mind in debugging an application that I inherited from a fellow developer who is absent. I have narrowed down the problem to the following place in code (php files are checked, Vue instances are initialised, there are no syntax errors).
This is my the component that gets initialised:
var RadniStol = Vue.component('radnistol', { template: '#template-RadniStol', data() { return { tableData: [], requestData: { sort: "ID", order: "DESC" } } }, methods: { reloadTable: function (event) { data = this.requestData; this.$http.post('php/get/radni_stol.php', data).then(response => { console.log(response.data.bodyText); this.tableData = response.data.records; }); }, . . .
The PHP file that gets called with the POST method is working correctly, querying the database and echoing the response in a JSON format.
The thing that is making me pull out my hair is the following: the console.log(response.data) outputs the following into the console:
{"records":[{"DODAN_NA_RADNI_STOL":"1","..."}]}
It is an JSON object that I expected to have but when trying to assign it to the data of the component with:
this.tableData = response.data;
or any other way… response.data.records returns ‘undefined’ in the console. I have tryed with JSON.parse() but no success.
When logging types to console: response variable is a response object with a status 200 and body and bodyText containing the data from the database. response.data is a string type containing the string JSON with the data from the database.
I am really starting to lose my mind over this issue, please help!
Thank you
Watch for data change
I'm currently struggling with the Vue instance concept. I'm using the vue-loader with webpack and created a vue component that I'm importing.
import Vue from 'vue'; import Search from '../Search.vue'; const vm = new Vue({ el: 'search', render: h => h(search) });On the component:
export default { data: function() { return { results: 'current results' } } }I want trigger and event from inside of the component (on a property change) that I can watch from the instance.
Using the API should be something like this:
vm.$watch('results', function (newVal, oldVal) { // do something })But I does not trigger anything.
I think I'm missing to understand how to use the Vue instance because I can't also add any data on initialization of the instance that is accessible on the component like:
const vm = new Vue({ el: 'search', data: {index: 1}, render: h => h(search) });Index is also not available inside of the component to use.
How do I fix this?
Failed to mount component using vue-js-toggle-button
I tried to use the plugin for a project with Vue 2 but got a Vue warn like below.
[Vue warn]: Failed to mount component: template or render function not defined
Inside vue component:
import ToggleButton from 'vue-js-toggle-button' export default { components: { ToggleButton } }Then,
<toggle-button :value="true" :labels="{checked: 'Foo', unchecked: 'Bar'}"/>The plugin is not that popular and any help would be much appreciated.
Laravel 5.5 bootstrap error
I am getting below error.
Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript.
app.js
require('./bootstrap'); window.Vue = require('vue'); import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import VueAxios from 'vue-axios'; import axios from 'axios'; Vue.use(VueAxios, axios); import App from './App.vue'; import Login from './components/Login.vue'; import Register from './components/Register.vue'; import Activity from './components/Activity.vue'; import SelectPersons from './components/SelectPersons.vue'; const routes = [ { name: 'Login', path: '/', component: Login }, { name: 'Register', path: '/register', component: Register }, { name: 'Activity', path: '/activity', component: Activity }, { name: 'SelectPersons', path: '/selectpersons', component: SelectPersons } ]; const router = new VueRouter({ mode: 'history', routes: routes}); new Vue(Vue.util.extend({ router }, App)).$mount('#app');bootstrap.js
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ try { window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); } catch (e) {} window.Vue = require('vue'); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Next we will register the CSRF Token as a common header with Axios so that * all outgoing HTTP requests automatically have it attached. This is just * a simple convenience so we don't have to attach every token manually. */ let token = document.head.querySelector('meta[name="csrf-token"]'); if (token) { window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo' // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });Here is the file that loads every vue component or blade template pages.
<html> <head> {{Html::style('/css/bootstrap.css')}} {{Html::style('/css/style.css')}} {{Html::script('/js/bootstrap.js')}} </head> <body> <div id="app"> </div> <script src="{{asset('js/app.js')}}"></script> </body> </html>I am using Laravel with vue. Can anybody help me to solve this issue?
Thanks
Vue JS v-attr=“expression1 && exp2 && exp3” are not working
Vue JS v-attr=“expression1 && exp2 && exp3” are not working. I am also tried ${&}${&} and like #{&}#{&} and && and also like
#{&}#{&}Code is available in JSFiddle
http://jsfiddle.net/yMv7y/3330/What framework to chose for the UI in an Enterprise Web Application?
I am working on an enterprise web application which is to be developed from scratch but traditionally the team has been using JSF for the UI with JE7 for the backend.
While JE7 is a great idea for the backend enterprise web app it is the front end that bothers me.
I am evaluating as to what could be a better framework for the front end instead of JSF? Maybe React or Vue or Angular or good old friend jQuery backed up by require.js for Asynchronous Module Definiton (AMD) of Javascript?
I read a number of posts as these :https://dzone.com/articles/vuejs-is-good-but-is-it-better-than-angular-or-rea and https://medium.com/reverdev/why-we-moved-from-angular-2-to-vue-js-and-why-we-didnt-choose-react-ef807d9f4163
If anyone has had the opportunity of a similar decision making before please share your learning.
P.S. I am aware that SO is not the right platform to post such a question but I could get the most meaningful insights on my thoughts only here.
Moving Logic from Directive to Method in Vue Compoment
I have a VueJS component that targets the style attr like this:
<section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: ['src'] } </script>Now, this works exactly as I wish it to (it includes the style attr if the user enters a image url and does not include it if he/she does not.
However, my understanding is that it is 'better' (in general) to separate my logic out into a method rather than include it within the :style directive.
Now, I am fairly new to VueJS and do not have a strong JavaScript backgrand and am trying to figure out how to do that, but have not been able.
As such, I'm wondering if someone could show me how to write a method (or some other recommend best practice) to achieve the same result.
Thanks.
Vue.js: Cannot find module './check-versions'
I'm developing a Vue.js app based on the webpack template generated by vue init webpack <name-of-project>.
Everything had been working just fine, but now when I try npm run dev or npm run build I get the error:
Error: Cannot find module './check-versions' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object.<anonymous> (C:\Users\Bertie\bertie-wheen-online\build\build.js:1:63) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3)I first tried generating a fresh project with vue init webpack test-webpack and compared a few key files (package.json, build/dev-server.js, build/build.js, build/webpack.base.conf.js) with the ones in my project to make sure nothing major had changed (except for my installing vue-resource and a couple of loaders for Sass and Slm, which had been working fine before). I also checked that the failing commands worked for test-webpack (to make sure it wasn't something with my system that had inexplicably gone wrong), which they did.
I then tried deleting my node_modules/ directory and re-npm install-ing, which didn't help.
Hopefully I'm missing something obvious, but I'm at a bit of a loss to figure out how to progress from here (unless I generate a fresh project and move everything across, but that feels unsatisfactorily like side-stepping the problem). What should I do? (If you need to look at any of my files to diagnose the problem, ask for them in a comment and I'll upload them.)
Vue.js dynamic two way data binding between parent and child components
I'm trying to use a combination of v-for and v-model to get a two-way data bind for some input forms. I want to dynamically create child components. Currently, I don't see the child component update the parent's data object.
My template looks like this
<div class="container" id="app"> <div class="row"> Parent Val {{ ranges }} </div> <div class="row"> <button v-on:click="addRange" type="button" class="btn btn-outline-secondary">Add time-range </button> </div> <time-range v-for="range in ranges" :box-index="$index" v-bind:data.sync="range"> </time-range> </div> <template id="time-range"> <div class="row"> <input v-model="data" type="text"> </div> </template>and the js this
Vue.component('time-range', { template: '#time-range', props: ['data'], data: {} }) new Vue({ el: '#app', data: { ranges: [], }, methods: { addRange: function () { this.ranges.push('') }, } })I've also made a js fiddle as well https://jsfiddle.net/8mdso9fj/96/
Vuex - Do not mutate vuex store state outside mutation handlers
Why do I get this error:
Error [vuex] Do not mutate vuex store state outside mutation handlers.
What does it mean?
It happens when I try to type the edit input file.
pages/todos/index.vue
<template> <ul> <li v-for="todo in todos"> <input type="checkbox" :checked="todo.done" v-on:change="toggle(todo)"> <span :class="{ done: todo.done }">{{ todo.text }}</span> <button class="destroy" v-on:click="remove(todo)">delete</button> <input class="edit" type="text" v-model="todo.text" v-todo-focus="todo == editedTodo" @blur="doneEdit(todo)" @keyup.enter="doneEdit(todo)" @keyup.esc="cancelEdit(todo)"> </li> <li><input placeholder="What needs to be done?" autofocus v-model="todo" v-on:keyup.enter="add"></li> </ul> </template> <script> import { mapMutations } from 'vuex' export default { data () { return { todo: '', editedTodo: null } }, head () { return { title: this.$route.params.slug || 'all', titleTemplate: 'Nuxt TodoMVC : %s todos' } }, fetch ({ store }) { store.commit('todos/add', 'Hello World') }, computed: { todos () { // console.log(this) return this.$store.state.todos.list } }, methods: { add (e) { var value = this.todo && this.todo.trim() if (value) { this.$store.commit('todos/add', value) this.todo = '' } }, toggle (todo) { this.$store.commit('todos/toggle', todo) }, remove (todo) { this.$store.commit('todos/remove', todo) }, doneEdit (todo) { this.editedTodo = null todo.text = todo.text.trim() if (!todo.text) { this.$store.commit('todos/remove', todo) } }, cancelEdit (todo) { this.editedTodo = null todo.text = this.beforeEditCache }, }, directives: { 'todo-focus' (el, binding) { if (binding.value) { el.focus() } } }, } </script> <style> .done { text-decoration: line-through; } </style>stores/todos.js
export const state = () => ({ list: [] }) export const mutations = { add (state, text) { state.list.push({ text: text, done: false }) }, remove (state, todo) { state.list.splice(state.list.indexOf(todo), 1) }, toggle (state, todo) { todo.done = !todo.done } }Any ideas how I can fix this?
Responsive Props in Vue Component
I have a prop called src in a Vue Component that binds to a :style like this:
<template> <section :class="color" class="hero" :style="{ backgroundImage: src && 'url(' + src + ')' }"> <slot></slot> </section> </template> <script> export default { props: ['src', 'color'] } </script>What I would like to do is to create a list of responsive props that get used depending on the device or screen size of the site visitor.
For instance, I imagine a list of props like src-sm, src-md, src-lg, etc. The user would enter different image urls for different device sizes and the style attr would use the appropriate url depending on the screen/size.
Is this possible in VueJS. If so, any idea how?
Thanks.
How to send cookie token using axios?
Here's my code for generating token that will response as a cookie.
And I'm using axios to process it. Here's my code:
Now, I'm having a problem on how to send the token to retrieve users list. I've tried to add withCredentials: true but no luck.
I got a response error token_not_provided.
Questions:
- How to get the value of the cookie token from response?
- How to send the token using axios with Authorization Bearer {token}?
Thank you In Advance.
vee-validate unable to validate a Combodate field
I am using vee-validate to validate a Combodate field. Combodate hides the text input and displays few drop down lists to pick a date. Validation using vee-validate does not work for this field. The behavior is weird.
This is how the field looks when I try to validate the form after selecting the date:
So see what is happening behind, I displayed the text input. When I selected the date, I can see the selected date in the text input.
But when I tried to click on the text input and then clicked somewhere else (on blur), the value from the text input gets removed and validation fails (validation is on blur).
If I don't blur the input when I submit the form, it starts validating the input, the value gets cleared and then the validation fails.
How can I fix this issue?
Pass object as prop on Vue
How do you go on passing objects as props on vue? I would imagine this would be a simple task but apparently not.
I have the following code on a .vue file:
`
<template> <div id="scatter"></div> </template> <script> export default { props: { data: { type: Object, default: () => ({}) } }, mounted () { console.log(this.data) } } </script>`
On html I try to pass the data props as follows :
<component :data="{x:1}"></component>
When I try lo log it into the console the result is only an empty observer object.
vue-js-modal draggable issue
I am using vue-js-modal, and have a issue with it, everytime i set my modal as :draggable="true" i can drag it but it don't let me write on the inputs, because i think it considers it as draggable elements too, how can i prevent it?
this is how i set it up:
<!-- modal dedicated to the panel history --> <modal :adaptive="true" height="70%" width="60%" :resizable="true" class="modalSize" :draggable='true' name="modalPanel"> <span class="cross" @click="$modal.hide('modalPanel')"> ✖ </span> <!-- here lives the panel history --> <appPanelHistory> </appPanelHistory> </modal>when the modal open i can't change my inputs, anyone know the issue? thanks
How to call a function when store has data
I have to create a video player object but I need the stream object to be present before I create the video player.
The this.stream is populated by vuex data store. but I find the mounted() and created() methods don't wait for store data to be present.
Here is the Player.vue component:
import Clappr from 'clappr'; import { mapActions, mapGetters } from 'vuex'; import * as types from '../store/types'; export default { name: 'streams', data() { return { player: null }; }, computed: { ...mapGetters({ stream: types.STREAMS_RESULTS_STREAM }), stream() { return this.$store.stream; } }, methods: { ...mapActions({ getStream: types.STREAMS_GET_STREAM }) }, mounted() { this.getStream.call(this, { category: this.$route.params.category, slug: this.$route.params.slug }) .then(() => { this.player = new Clappr.Player({ source: this.stream.url, parentId: '#player', poster: this.stream.poster, autoPlay: true, persistConfig: false, mediacontrol: { seekbar: '#0888A0', buttons: '#C4D1DD' } }); }); } };Is there a way to wait for this.stream to be present?
VueJS 2 + ASP.NET MVC 5
I'm very new with VueJS. I have to build a single page application inside a ASP.NET MVC5.
I follow this tutorial and works very well -> TUTORIAL
But when i create a .vue page to test VueJS2 Routes, the browser does not understand "Import", i read that i have to use a transpiler like Babel, someone know how i solve it?
App.VUE
<template> <div id="app"> {{msg}} </div> </template> <script> export default { name: 'app', data () { return { msg: 'Welcome to Your Vue.js App' } } } </script>App.JS
import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', router, render: h => h(App), data: { message: 'Hello Vue! in About Page' } });_Layout.cshtml
<div class="container-fluid"> @RenderBody() <div id="app"> { { message } } </div> </div> <script src="~/Scripts/essential/jquery-3.1.1.min.js"></script> <script src="~/Scripts/essential/bootstrap.min.js"></script> <script src="~/Scripts/essential/inspinia.js"></script> <script src="~/Scripts/essential/vue.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.0.1/vue-router.js"></script> <script src="~/Scripts/app.js"></script> <script src="~/Scripts/plugin/metisMenu/jquery.metisMenu.js"></script> <script src="~/Scripts/plugin/pace/pace.min.js"></script> <script src="~/Scripts/plugin/slimscroll/jquery.slimscroll.min.js"></script>Thanks a lot!!
make a vue component html refresh
I have a vue.js component that has an array of elements on his data and it's html it's something like this:
<component2> <div v-for="element in Email.elements" :id="element.id"> <component3 :element="element" > </div> </component2>I can manage component 1 and 3. Component 2 is external code that I can't see or manipulate. When I delete 1 element everything breaks, but when I load component 2 with a new array of elements it works fine. Is there any way to force a reload of a component HTML?
Cannot access element shown by v-if in component mounted callback
Regardless if I use this.$refs or this.$el, I'm only able to access the loader div (<div class="ui active inline loader"/>).
How am I supposed to access an element which doesn't exist when the component is mounted? Do I have to change v-if to v-show?
Reactive data inside an object VueJS
I have an array of objects like this:
buttons: [ { name: 'ok', action: this.onOk, disabled: this.disabledButton }, { name: 'reset', action: this.onReset } ]This array is sent to a child component as a prop.
Now, the disabledButton parent variable will change on different ocasions... Is there a way to also make my button disabled property change (without watchers and recreating the array) ??
Thank you