Software
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
how to hide dropdown menu if we click outside the menu in vuejs
I am using a dropdown menu components in vuejs to make normal dropdown menu. My code is for dropdown component is :
<template> <span class="dropdown" :class="{shown: state}"> <a href="#" @click.prevent="toggleDropdown" class="dropdown-toggle">toggle menu</a> <div class="dropdown-menu" v-show="state"> <ul class="list-unstyled"> <slot></slot> </ul> </div> </transition> </span> </template> <script> export default { name: 'dropdown', data () { return { state: false } }, methods: { toggleDropdown (e) { this.state = !this.state; } } } </script>Now I am importing the dropdown component in my VUE app at various place by using following code in the template
<dropdown> <li> Action </li> </dropdown>Now that is working fine but I want that only one dropdown should be active at the same time.
I have done little research and found that i can use plugins like https://github.com/davidnotplay/vue-my-dropdown but I don't want to use that. Again i have also studied how the above example works but I want to implement this dropdown functionality in such a way that my dropdown component would take care of all event related to dropdown. So can you help me how to achieve that?
Array child in conditional rendering in vue.js
I have api on laravel and front on vue + laravel. I am getting all the data from api and pass it to view. Now I want to do conditional rendering.
My array looks like:
"data" => array:2 [▼ 0 => array:5 [▶] 1 => array:5 [▶]I want to show div if topic from link is the same topic from array. But I do not know how to search and compare that words. So it will be like that:
v-if="$topic == this.topic"But now I can only use
v-if="$data[]['0']['topic']"and then I have the same topic on all my views.
My link looks like:
/user/{topic}/postHow to do it correctly guys?
Why doesnt node express include my vue file?
So i have two script files that I am trying to include. one is a javascript file and the other a vue file.
the javascript file gets included but for some reason the vue file does not get included. I do not get any errors.
three structure:
hbs page:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> --> <link rel="stylesheet" type="text/css" href="/Static/css/spaceGame.css"> <!-- <link rel="stylesheet" href="css/normalize.css"> --> <link href="https://fonts.googleapis.com/css?family=Raleway:300,400" rel="stylesheet"> <title>{{title}}</title> </head> <body> {{{body}}} <!-- Footer --> <script src="https://unpkg.com/vue"></script> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="/Static/script/space.js"></script> <script type="text/javascript" src="/Static/script/someTest.js"></script> </body> </html>script:
var express = require('express'); var hbs = require('express-handlebars'); var app = express(); var orgininPath = require("path"); var routes = require(orgininPath.resolve('./hoast/routerHandler/routes')); app.listen(3000, function() { console.log('Listening on port 3000'); }); app.use(express.static(orgininPath.join(orgininPath.resolve('./'), 'public'))); var url = require('url'); app.engine('hbs', hbs({ extname: 'hbs', defaultLayout: 'layout', layoutsDir: orgininPath.resolve('./Views/Layout/') })); app.set('view engine', 'hbs'); app.use('/', routes); module.exports = app;Browser includes js file but now vue file:
What am I missing?
Debugging UI Tests written with Testcafe
We are using Testcafe + Webpack + Vue.js for our project. I know that it is possible to debug the test code either by t.debug() directive or --inspect flag of node.js.
However, I can only see the production code (bundle.js) which is obfuscated and not really debuggable. I wonder if it is possible to have a configuration so that the testcafe does not use the bundled code but rather the original source code (probably with sourcemaps?). I am using source-map as the devtool option in webpack.
I am aware that the UI tests should test the production code but it would be nice to have such a configuration while developing. Any ideas?
Vue get current component as a node?
I need to get the current position of a Vue component in the DOM. I know that I can get the HTMLElement of a component by using:
this.$elThis is not a node though. I need to be able to perform an appendChild on the current component so therefore I need a node.
Is there a proper way to do this?
Passing a jquery variable to vue js
I have this code that posts some data to a remote server and receives the success message. I am getting an array and i am using that array to contain various pieces of data. I want to use a particular data to show if the direction of a trad is up or is down using vue js.
This is the jquery code
var email = window.localStorage.getItem("email"); var rid = window.localStorage.getItem("rid"); var ob = { 'email' : email, 'id' : rid }; var data = decodeURIComponent($.param(ob)); setInterval(function() { $.ajax({ url: 'http://example.world/mobile/index.php/welcome/my_trade_details', type: 'POST', data: data, success: function (data) { data = JSON.parse(data); $('#started_at').html(data.trade_start); $('#ended_at').html(data.trade_end); $('#my_trade_is').html(data.trade_direction); $('#result_is').html(data.trade_result); $('#trade_status').html(data.trade_status); $('#concurrency').html(data.trade_concurrency); $('#amount').html(data.trade_amount); $('#etherum_contract_number').html(data.etherum_contract_number); }, error: function (data, textStatus, jqXHR) { if(typeof data === 'object'){ var data = 'No Internet Connection Detected'; } } }); }, 5 * 1000);and this is the vue js code
<div v-if="trade_direction === 'up'"> <i class="green material-icons">arrow_upward</i> </div> <div v-else> <i class="green material-icons">arrow_downward</i> </div>How can i define and pass the variable trade_direction between jquery and vue js?.
Vue/css - how to use :last-child selector when looping over items
I have articles array, through which I loop and create media objects for each of them. This is the parent component:
<div v-for="article of mostReadNews" class="most-read"> <media-object :article="article"></media-object> </div>And this is the template of the media-object component:
<template> <router-link :to="article.link"> <article class="media"> <figure class="media-left"> <p class="image is-96x96"> <img :src="article.image.data.path"> </p> </figure> <div class="media-content"> <div class="content"> <h6 class="is-6">{{ article.title }}</h6> <span class="time-icon"><i class="material-icons">query_builder</i> {{ createdAt }}</span> </div> </div> </article> </router-link> </template>The problem I have is that if I set with :last-child styling, like in my case, where I am setting the border-bottom for each element, except for the last one, it overwrites the first rule and none of the elements get border. I have tried with setting the css both in parent and child component, as well as in the theme.scss, but every time the border bottom of the last child selector overwrites the border bottom that I have set up for other items. This is the css:
<style scoped lang="scss"> @import "../assets/theme"; article { border-bottom: 1px solid $grey-lighter; } article:last-child { border-bottom:none; }How can I fix that?
Configure RouteConfig in vue.js
I use Vue.js 2.3, I want to define my own class for active href.
I saw 'linkActiveClass' option in the doc, but I can't figure out how to use it. I tried directly in code :
<router-link :to="{path : 'about', linkActiveClass: 'active', exact: true}" class="item" :linkActiveClass="active"><i class="icon talk"></i> About</router-link>It doesn't work. I think I can define it in RouteConfig, but how to do that ? I see nothing in doc.