Software
Mounting VueJS to top level div & user submitted content
I'm building an small guide website which allows users to submit articles about a game. There are a number of components on the website written in Javascript, using VueJS. The majority of the site is powered by Laravel and renders in plain HTML except these components. At the moment, I have VueJS mounted to #app, or my top level div element, as is default with the Laravel configuration.
I then drop components into the page as usual () and VueJS will pick these up and render them appropriately. Awesome.
However, there are a few situations where user submitted content will actually break the page. For example, if double brackets are used {{ example }}, this is VueJS syntax, and it will pick up the tags and refuse to render the page. Another example is if I need to use tags in the body which aren't VueJS, for example embedding a Twitch TV stream.
It seems like because Vue is mounted to #app, absolutely everything inside that shares VueJS syntax or is a script tag will break the page.
Is mounting to #app the wrong idea? Should I be splitting all of my components and somehow launching them with more granularity? I really like the approach of just dropping in Vue components into code with .
Thanks!
Ask for front end book recommendation [on hold]
I'm asking this question on behalf of my friend.
I want to get a front-end job next year. There's about half a year for me to practice. I have the basic knowledge of html/css/js. Now I want to learn some architecture to do some projects.
I'd like to follow some books' guide and develop a website. Any recommendation?
Here's the requests:
- The book will teach you step by step to develop a website. The ideal situation is that the book develops a website, and each chapter adds some components and functions to this website.
- The book uses and teaches you to use one architecture like vue.js, angular.
- The book includes back-end knowledge, if the back-end is node.js, it would be perfect.
Can anyone give me some recommendations? Web tutorial and book are both ok!
Thanks in advance.
How to get random element in Vue.js
I have 3 hero images and their content and I want to display them randomly when user refreshes the page!
Basically I am trying to display random div using Jquery on loading page, but issue is that the size of hero image is large and by using Jquery, all these 3 images start loading in DOM which affects the speed of page.
Is there any solution for this in Vue.js for loading that one specific div at a time, not all 3 divs when user refreshes the page!?
jQuery Code:
mounted() { var random = Math.floor(Math.random() * $('.slider-item').length); $('.slider-item').eq(random).show(); },How do you import components having same name on Vue Router
I'm working on a VueJs project and now structuring my router records. I've realized I could be having different components having same name. How do I import them and use them in the route records? How do I make their names unique when configuring the router?
import Vue from 'vue' import Router from 'vue-router' import AllUsers from '../components/Sales/AllUsers' import AllUsers from '../components/Finance/AllUsers' ... export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/sales/users', name: 'sales-users', component: AllUsers }, { path: '/finance/users', name: 'finance-users', component: AllUsers }I have used a hypothetical example here (since I could as well call the components SalesUsers and FinanceUsers) but you will agree there are times when components will really have same name. How do I handle that, given that I need to specify the component for each route record?
PS: Slightly new to VueJS, so advice on improvements and best practices is welcome.
Vuejs single file component (.vue) model update inside the <script> tag
I'm new to vuejs and I'm trying to build a simple single file component for testing purpose.
This component simply displays a bool and a button that change the bool value. It also listen for a "customEvent" that also changes the bool value
<template> {{ mybool }} <button v-on:click="test">test</button> </template> <script> ipcRenderer.on('customEvent', () => { console.log('event received'); this.mybool = !this.mybool; }); export default { data() { return { mybool: true, }; }, methods: { test: () => { console.log(mybool); mybool = !mybool; }, }, }; </script>The button works fine. when I click on it the value changes. but when I receive my event, the 'event received' is displayed in the console but my bool doesn't change.
Is there a way to access the components data from my code?
Thanks and regards, Eric
Symfony 3 routes + VueJS's index.html with F5 falls to 404
I try connect Vue.js with Symfony 3, but have no idea how to create proper route configuration for it. Project tree looks like that:
Project root - app/ - Resources/ - views/ - default/ - web/ - assets/ - static/ index.html // here Vue is includedFrom Symfony I provide some REST API, the routes to it are prefixed by /api/. And I have some routes in Vue SPA. The problem is if I press F5 in browser on any Vue route, which of course is not included in my routing.yml, browser returns 404 error from Symfony. One half-working decision is when I put content of index.html to Resourses/views/default/twig with such a route:
fallback_for_vue: path: /{req} defaults: { _controller: 'AppBundle:Default:index' } requirements: req: ".+",taken from another question, but this is not actually what I need, because I don't want my frontend programmer to go somewhere except web/ folder. So which configuration of Symfony routes I should use?
Vue - named exports in *.vue files are ignored
I am getting warnings in the console that the:
named exports in *.vue files are ignored.
On looking around about the problem I came across this where it is suggested that if I upgrade the vue loader to the version 8.3.1 that all the warnings are gone. On checking the package.json file in the node_modules/vue-loader folder I saw that I already have that version:
{ "_args": [ [ { "raw": "vue-loader@^8.3.1", "scope": null, "escapedName": "vue-loader", "name": "vue-loader", "rawSpec": "^8.3.1", "spec": ">=8.3.1 <9.0.0", "type": "range" },How can I fix this and get rid of this warnings?
pass dragable v-for option to function when drag is over
I want to drag a element from list 1 to list 2 and call a method when i leave the drag, i almost accomplish everything with it, my only problem here is that i only can put the @end(responsable for detecting the end of dragging) in the draggable tag, and the div that has the v-for is a child from it, so i can't get the element from the list to pas to a function in my draggable.
This is my code:
<draggable v-model="sectionList" class="dragArea" @end="changeView(section.component)" :options="{group:{ name:'sections', pull:'clone', put:false }}"> <transition-group name="list-complete"> <div v-for="(section, index) in sectionList" @click="changeView(section.component)" :key="section.text" class="card card-color list-complete-item"> <div class="card-block"> <h4 class="card-title text-center">{{section.text}}</h4> </div> </div> </transition-group> </draggable>the @end=changeView receives a parameter, that parameter should be the section.component that comes from the list, any help to get the element?
Thank you
Filtering in Vue, nested array
Im trying to create a computed function that can filter out my Object by "alarms",
So I've created a computed function, called filteredAlarms, and in my loop im doing a v-for loop:
<li class="event-log__item timeline__item" v-for="(item, key) in filteredAlarms" :key="key">And in my filter im trying to do the following:
let filteredAlarms = Object.keys(this.eventLog).forEach(key => { this.eventLog[key].filter(item => { return item.type.indexOf("alarm") > -1 }); }); return filteredAlarmsUnfortunately, this doesn't work - Im getting a an error: TypeError: this.eventLog.filter is not a function
What am I doing wrong? :)
The object im trying to filter is something similar to the one below:
"system_events": { "1013": [{ "id": 25899, "timestamp": "2017-08-15T21:26:42Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:26:40Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Randers pr 44b sidste station" }, { "id": 26157, "timestamp": "2017-08-15T21:32:17Z", "type": "warning", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:32:06Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Randers pr 44b sidste station" }, { "id": 26387, "timestamp": "2017-08-15T21:37:38Z", "type": "info", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:37:33Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Randers pr 44b sidste station" } ], "1015": [{ "id": 23777, "timestamp": "2017-08-15T20:38:08Z", "type": "alarm", "code": 191, "title": "", "description": "", "appeared": "2017-08-15T20:38:00Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" }, { "id": 23779, "timestamp": "2017-08-15T20:38:08Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T20:37:58Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" }, { "id": 23841, "timestamp": "2017-08-15T20:39:41Z", "type": "alarm", "code": 192, "title": "", "description": "", "appeared": "2017-08-15T20:39:31Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" }, { "id": 25243, "timestamp": "2017-08-15T21:12:03Z", "type": "alarm", "code": 191, "title": "", "description": "", "appeared": "2017-08-15T21:11:55Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" }, { "id": 25529, "timestamp": "2017-08-15T21:18:11Z", "type": "alarm", "code": 190, "title": "", "description": "", "appeared": "2017-08-15T21:18:00Z", "disappeared": null, "acknowlegded": null, "solved": null, "system_name": "Favrskov Svenstrup gyvelvej" } ],} ]
}
Redraw highchart on vue model
I am trying to use vuejs and highchart on displaying the data. When I change the model, I want to redraw the chart data. Any idea ? This is what I tried to do?
var options = { title: { text: 'Temperature ', x: -20 //center }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] }, yAxis: { title: { text: 'Temp' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: '' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, series: [{ name: 'Japan', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }, { name: 'Australia', data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8] }] };For the Vue
return new Vue({ el: '#app', data: { modelValue = '', options:options }, methods: { changetemp = function(){ //The option value should be change here } },When the model value is changed, I want the options to be redrawn
How to show list dom revered in vue js?
I want to show my vue js list in v-for reversed on dom. Object should not be change. Just created reversed list by v-for. HTML default list is top to bottom, I want to append items from bottom to top in dom. You can see telegram web messages list that do this with ng-repeat.
Is there any way to do this by v-for? or another option?
Thanks.
How can I get data inside of Vue from database like config or smth>
I have configs for my app in database and I want to use them inside of Vue instance (here are positions of my elements). But when im getting "this.positions.positions" Im getting empty string.. How can I do that?
how to mock module when using jest
I'm using Jest for unit test in a vuejs2 project but got stuck in mocking howler.js, a library imported in my component.
Suppose I have a component named Player.vue
<template> <div class="player"> <button class="player-button" @click="play">Player</button> </div> </template> <script> import { Howl } from 'howler'; export default { name: 'audioplayer', methods: { play() { console.log('player button clicked'); new Howl({ src: [ 'whatever.wav' ], }).play(); } } } </script>then I have its test file named Player.spec.js. Test code was written based on the answer here, but the test failed since called wasn't set as true. It seems that mocked constructor won't be called when running this test.
import Player from './Player'; import Vue from 'vue'; describe('Player', () => { let called = false; jest.mock('howler', () => ({ Howl({ src }) { this.play = () => { called = true; console.log(`playing ${src[0]} now`); }; }, })); test('should work', () => { const Constructor = Vue.extend(Player); const vm = new Constructor().$mount(); vm.$el.querySelector('.player-button').click(); expect(called).toBeTruthy(); // => will fail }) })Though I'm using Vuejs here, I considered it as a more general question related to the usage of Jest's mock API, but I'm not able to get further.
Where do I store shareable data in vuejs?
I am building an app with various pages, and when users goes to /orgs I have a template that I require
// routes.js ... import Orgs from './components/Orgs.vue'; ... { path: '/orgs', component: Orgs, meta: { requiresAuth: true } },from here I have a simple template in Orgs.vue that looks like:
<template lang="html"> <div> {{orgs}} </div> </template> <script> export default { data(){ return { orgs: []; } }, created() { //use axios to fetch orgs this.orgs = response.data.orgs; } } </script>The problem is that if I want to show list of organizations in other pages, I am bound to duplicate the same code for other pages as well, but I am trying to find a solution that would call return organizations so I can use that in multiple page?
What is the solution for this?
Vue js computed result not accurate
I am trying to implement a vote button with vue js, when user click "Vote" will send axios request to server and store the data, then return json back. Same with unvote. I also check if the user is voted, the button should change to Unvote like facebook. So far the vote and unvote button is work correctly. But i found a problems which is the voted features is not working. If user voted, after refresh page it will change back to "Vote", but it should be Unvote. But if the button was clicked, in database will showing the vote was deleted. Mean it should be problems of computed. But i am struggle on it since i not really know vue js.
This is my vue components.
<template> <a href="#" v-if="isLiked" @click.prevent="unlike(comment)"> <span>UnVote</span> </a> <a href="#" v-else @click.prevent="like(comment)"> <span>Vote</span> </a> <script> export default{ props: ['comment','liked'], data: function() { return { isLiked: '', } }, mounted() { axios.get('/comment/'+ this.comment.id +'/check', {}) .then((response) => { this.liked = response.data;//here will get json "true" or "false" }); this.isLiked = this.liked ? true : false; }, computed: { isLike() { return this.liked; }, }, methods: { like(comment) { axios.post('/comment/'+ comment.id +'/like') .then(response => this.isLiked = true) .catch(response => console.log(response.data)); }, unlike(comment) { axios.post('/comment/'+ comment.id +'/unlike') .then(response => this.isLiked = false) .catch(response => console.log(response.data)); }, } }Parent rerenders every time nested route changes
I have a project with a simple folder structure similar to the following:
pages/ --items.vue --items/ ----_id.vueI have included a <nuxt-child/> inside items.vue along with a list of items that link to different id's. _id.vue simply renders a modal that displays info based on the id passed as a param.
This is all working and rendering properly except that each time an item is clicked, the items.vue component re-renders causing it reset its state and lose the users scroll position.
Is this expected behavior? Is it possible to have dynamic nested routes without re-rendering their parent with each route change?
Adding external library to vuejs
I am new to web development scene and recently started to dive into it, still getting a hang on how stuff are wired up in the background process by webpack.
I am trying to get wow.js which I installed by npm to work in all my Vue components. So I was wondering how do I include wow.js globally, such that all my future Vue component will be able to use wow?
I included the following in my index.html, but it didn't work.
<script src="node_modules/wowjs/dist/wow.min.js"></script><script>new WOW().init();</script>>But when I do the following, which fetches it from a CDN, it works.
<script src="//cdnjs.cloudflare.com/ajax/libs/wow/0.1.12/wow.min.js"></script><script>new WOW().init();</script>>Although it works if I use the CDN method, but I want to find out the proper way to include npm installed dependencies
vue 2.3 AJAX data binding not updating
After a successful ajax call the data rendered on the page is not updating. It is remaining empty / null.
It seems that I am missing how to connect the data returned as a front end variable and the dynamically / live rendered html elements.
Here is the relevant code snippets for context. Is it clear from this what is missing / incorrect?
Javascript
page = new Vue({ el: "#container", data: { option_id: null, option_name: null }, created:function() { $.ajax({ type: 'POST', contentType: 'application/json', dataType: 'json', url: 'ajax_methods/get_option', success: function (ajax_data) { self = this; self.option_id = ajax_data.option_id; self.option_name = ajax_data.option_name; }, error: function (e) { console.log(e) } }) } })HTML
<script type="text/javascript" src="https://unpkg.com/vue@2.3.3"></script> <div id="container"> <p>{{ option_name }}</p> <button v-on:click="send_option()" type="button" id="left_button" name="left_button" v-bind:value="option_id"> </div>Checking AJAX success
When entering the following in the console, non null values come back as expected:
- self.option_id
- self.option_name
Vue.js consume json
My problem is with this json. http://dev-rexolution.pantheonsite.io/api/noticias
I need to consume with vuejs 2 only the first element of the array to be able to display it, working with the console I worked but with no vuejs.
This console log work: console.log(response.data[0].title[0].value);
<template> <div class="Box Box--destacado1"> <div class="Media Media--rev"> <div class="Media-image"> </div> <div class="Media-body"> <span class="Box-info">{{ noticias[0].field_fecha[0].value}}</span> <h3 class="Box-title"> <a href="">{{ /*noticias[0].title[0].value */}}</a> </h3> <p class="Box-text">{{/*noticias[0].field_resumen[0].value*/}}</p> </div> </div> </template> <script> import axios from 'axios'; export default { data: () => ({ noticias: [], errors: [] }), // Fetches posts when the component is created. created() { axios.get(`http://dev-rexolution.pantheonsite.io/api/noticias`) .then(response => { // JSON responses are automatically parsed. this.noticias = response.data }) .catch(e => { this.errors.push(e) }) } } </script>Passing event methods in Vue
I'm trying to determine how to pass an event down with a bound change listener to a child input component. I'm using wrapped input components, but want to be able to define methods in the parent component.
//App.js: <currency-input :input="changeInput" :value="inputs.name"></currency-input> <input :input="changeInput" :value="inputs.address"></input> <script> export default: { changeInput(e) { this.$store.dispatch('changeInput', e); } } <script> //currency-input <masked-input type="currency" class="currency-input" :mask="currencyMask"> </masked-input> //store.js vuex action changeProp: function( state, e ){ state.dispatch('change_prop', e.target.name, e.target.value); }This fires on the 'input', but not on the 'currency-input'. If I add @input prop to the currency-input and bind it to the masked-input's @input, then the function runs but the value of 'e' is just the input value, not the event.
Why is this happening and how can I pass the function so that the parameter ends up being the event itself?