Software
Vue.js render child component to variable to be used within component
I'm using webpack and vue.js 2 and vue-google-maps. I have an issue where i need to pass to a google maps component via a prop a rendered vue-template.
e.g.
<gmap-info-window :options="infoOptions" :position="infoWindowPos" :opened="infoWinOpen" :content="infoContent" @closeclick="infoWinOpen=false"> </gmap-info-window>i need to pass to the :content prop. something along the lines of this:
<p> Some Name <a :href="some.url" target="_blank" @click="myFunction('param1', $route.name, param2)">some link</a> <p>basically i need infoContent to be the vue compiled version of the above. I can get the template e.g. by doing:
this.infoContent = myTemplate;but that only gets me the raw unrendered version of the template if i add .render() to that i start getting errors about _vm._self is undefined"
Check if json array is empty at store vuex
I want to show a button if my array of object has some data, so basilcy in my store(vuex) i defined a array like this:
state: { document: [] },i append data to this array from other components and i already checked that the data is appending right, no problem here.
So i want to show the button just if there is some data:
<div class="row margin-above"> <div class="panel panel-primary" v-for="section in this.$store.getters.getDocument"> <div class="panel-body quote" > <p>{{section.key}}</p> </div> </div> <div v-if="this.$store.getters.getDocument != '[]'"> <button class="btn btn-success btn-block">Create Document</button> </div> </div>there is the button, i want to hide the whole div with the button if the condition matches, but it is not working the button is always there, any help?
How can you dynamically render custom components in Vue using JSX? Please as soon as possible.Thanks
For example, the dynamic render drop-down box has default values and can also toggle the value of the drop down box?
VueJs renders all elements upon a single change
I have the following sample grid in which I push some new values to the bound list.
Press anywhere in the grid to push a new value to the grid.
As you can see in the fiddle, the updated cell will have a green color for 500 ms, and all the re-rendered elements will have yellow color.
The question is how we should configure Vue component so that it only re-render the changed element instead of them all?
If you look at the fiddle console output, you will see numbers like (13001, 26001, ...) and this equals to the number of all cells (1000 rows x 13 columns).
.yellow { background-color: yellow; } .pushed { background-color: lightgreen } <script src="https://unpkg.com/vue"> var globalCount = 0; </script> <head> <title>Vue Render Performance</title> </head> <div id="demo"> <demo-grid :data="gridData" :columns="gridColumns"> </demo-grid> </div> <script type="text/x-template" id="grid-template"> <table @click="pushData()"> <thead> <tr> <th v-for="key in columns"> {{key}} </th> </tr> </thead> <tbody> <tr v-for="(entry, i) in data"> <td v-for="(key, j) in columns" :id="'a'+i +'_'+j"> {{renderMe(entry[key], 'a'+i +'_'+j)}} </td> </tr> </tbody> </table> </script> <script> const data = newData(1000); var renderedCount = 0; var startTime = performance.now(); Vue.component('demo-grid', { props: { data: Array, columns: Array, renderCount: Object, }, template: '#grid-template', methods: { renderMe(el, id) { const elm = document.getElementById(id); if (elm) { elm.className += " yellow"; } if (!renderedCount) { renderedCount = 0 } else { renderedCount++; } return el; }, pushData() { debugger var push = function() { let cols = ["Col1", "Col2", "Col3", "Col4", "Col5", "Col6", "Col7", "Col8", "Col9", "Col10", "Col11", "Col12", "Col13"]; var t0 = performance.now(); for (let i = 0; i < 1; i++) { let newVal = Math.random() * 10000, row = Math.round(Math.random() * 1000), cellIndex = Math.floor(Math.random() * cols.length); cell = cols[cellIndex]; if (data[row]) data[row][cell] = newVal; var el = document.querySelector('tbody tr:nth-child(' + row + ') td:nth-child(' + cellIndex + ')'); if (el) { el.className = 'pushed'; el.scrollIntoView(); var t = function() { if (el) { el.className = ''; } clearTimeout(t); }; setTimeout(t, 500); } console.log('pushed to cell [' + row + ',' + cellIndex + '] :' + newVal); console.log('Rendered Count: ' + renderedCount) renderedCount++; }; var t1 = performance.now(); console.log(t1 - t0) }; push(); } } }); // bootstrap the demo var demo = new Vue({ el: '#demo', data: { searchQuery: '', gridColumns: ["Col1", "Col2", "Col3", "Col4", "Col5", "Col6", "Col7", "Col8", "Col9", "Col10", "Col11", "Col12", "Col13"], gridData: data } }) Vue.config.devtools = true; function newData(count) { const data = []; for (let i = 0; i < count; i++) { data.push({ Col1: "Record", Col2: 818959475, Col3: 467587749, Col4: 438, Col5: 439, Col6: 440, Col7: 2.1, Col8: 436.2, Col9: 2.4, Col10: 5770, Col11: 5771, Col12: 5772, Col13: 5773 }); } return data; } </script>
Absolute path in vueJS
I'm working in a vue file inside of a Symfony project and I want to find the absolute path from a route. Usually i do something like that :
this.$http({ url: 'products/edit/'+product.id, method: 'PUT', params : params [...]and it works great. But now i don't need to use this.$http because i'm trying to do that :
<div> {{ getUrl(product) }} </div>and I have my fonction :
getUrl(product) : { let url = '/products/edit'+product.id return url }but obviously it only display : /products/edit/xxx instead of mysite.com/products/edit/xxx in production or localhost/products/edit/xxx in local. In my routing file I have :
update_product: path: /products/edit/{product} defaults: { _controller: RBProductsBundle:Product:edit }Content Security Policy error with Vue JS, Webpack and JSP
I am trying to integrate Vue JS in one of my application with latest version 2.4.2.Backend implementation uses struts and we set Content-Security-Policy script-src 'self' 'unsafe-inline' in response headers.
At first I was trying to use standalone Vue JS instead of using webpack or any other tool. I see the following CSP error when I execute my page using Vue JS :
[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.
warn — vue.min.js:485 compileToFunctions — vue.min.js:9842 $mount — vue.min.js:10040 Global Code — example.do:51To avoid this issue, I have started using webpack to pre-compile the templates so that the issue will be resolved and I still see the below error in webpack JS :
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: "script-src 'self' 'unsafe-inline'".
Is there any solution to use webpack / Vue JS with CSP's enabled ? What is the suitable solution to handle CSP issues.
Sample Example : Vue is not detected when JSP is loaded through struts
Thanks for your help in advance.
Vuejs / axios child component not passing through object
I have the following components:
Users
Addresses
Inside the Users component I have the following:
<script> export default { data() { return { address: null } } } </script>Inside the view, I have the following (calling the child component)
<partials-addresses source="/users" title="Users Address" @addressChanged="address = $event" placement="address" />This is then sent to an endpoint (using axios):
submitForm: function() { var vm = this; console.log(vm.address); // is fine, returns the object axios.post(`/users`, { address: vm.address }); }The issue is that when I'm outputting the data on the endpoint side, I'm just getting an empty array. I'm using another child component and this sends data through fine, it's just the address one.
Could it be because of the way the data is formatted?
v-if, v-for breaking dependent selects logic
I'm trying to implement dependent selects using Vue.js (last version), but my app logic breaks when I have a few v-for and v-if. I can't understand where is my mistake. Please, help me solve the problem.
Click Toggle !pickup and try to change District select and you'll see issue. You can also delete div with v-if="!cartPage.pickup" or change v-if to v-show, and you can see, everything is working..
Here is my code
var vm = new Vue({ el: '#app', data: { userInfo: { loggedIn: false, }, cartPage: { pickup: false, restaurants: {}, currentCity: '', currentDistrict: '', currentRestaurant: '', }, }, methods: { setDefaultDistrict: function() { this.cartPage.currentDistrict = this.cartPage.currentCity.districts[0]; this.setDefaultRestaurant(); }, setDefaultRestaurant: function() { this.cartPage.currentRestaurant = this.cartPage.currentDistrict.restaurants[0]; }, }, }) vm.cartPage.restaurants = [{ city: "City 1", districts: [{ districtName: "City 1 district 1", restaurants: [{ placeName: "City 1 district 1 Restaurant 1", name: 'City 1 district 1 Restaurant 1', address: 'City 1 district 1 Restaurant 1', hours: '10:00–22:00', }, { placeName: "City 1 district 1 Restaurant 2", name: 'City 1 district 1 Restaurant 2', address: 'City 1 district 1 Restaurant 2', hours: '10:00–20:00', }] }, { districtName: "City 1 district 2", restaurants: [{ placeName: "City 1 district 2 Restaurant 1", name: 'City 1 district 2 Restaurant 1', address: 'City 1 district 2 Restaurant 1', hours: '12:00–22:00', }, { placeName: "City 1 district 2 Restaurant 2", name: 'City 1 district 2 Restaurant 2', address: 'City 1 district 2 Restaurant 2', hours: '12:00–22:00', }] } ], }, { city: "City 2", districts: [{ districtName: "City 2 district 1", restaurants: [{ placeName: "City 2 district 1 Restaurant 1", name: 'City 2 district 1 Restaurant 1', address: 'City 2 district 1 Restaurant 1', hours: '10:00–22:00', }, { placeName: "City 2 district 1 Restaurant 2", name: 'City 2 district 1 Restaurant 2', address: 'City 2 district 1 Restaurant 2', hours: '10:00–20:00', }] }, { districtName: "City 2 district 2", restaurants: [{ placeName: "City 2 district 2 Restaurant 1", name: 'City 2 district 2 Restaurant 1', address: 'City 2 district 2 Restaurant 1', hours: '12:00–22:00', }, { placeName: "City 2 district 2 Restaurant 2", name: 'City 2 district 2 Restaurant 2', address: 'City 2 district 2 Restaurant 2', hours: '12:00–22:00', }] } ], }, { city: "City 3", districts: [{ districtName: "City 3 district 1", restaurants: [{ placeName: "City 3 district 1 Restaurant 1", name: 'City 3 district 1 Restaurant 1', address: 'City 3 district 1 Restaurant 1', hours: '10:00–22:00', }, ] }, ], }, ] vm.cartPage.currentCity = vm.cartPage.restaurants[0]; vm.cartPage.currentDistrict = vm.cartPage.currentCity.districts[0]; vm.cartPage.currentRestaurant = vm.cartPage.currentDistrict.restaurants[0]; .custom-radio { display: block; margin: 10px; border: 1px solid #000; cursor: pointer; } <script src="https://unpkg.com/vue@2.4.2"></script> <div id="app"> <div class="cart__delivery-and-pay"> <h2 class="cart__delivery-and-pay--title">Heading</h2> <div class="delivery__block"> <div class="delivery__block-header cf"> <div class="delivery__variants"><span @click="cartPage.pickup = false" v-bind:class="{ 'active': !cartPage.pickup }" class="courier custom-radio">Toggle pickup</span><span @click="cartPage.pickup = true" v-bind:class="{ 'active': cartPage.pickup }" class="pickup custom-radio">Toggle !pickup</span></div> </div> <div class="delivery__cols"> <!-- if delete this everything is working! --> <div v-if="!cartPage.pickup" class="delivery__col delivery__address"> <div class="delivery__col-heading">Address: <div class="custom-select__wrapper item__option"> <select class="custom-select"> <optgroup label="Choose city"> <option value="1" v-for="singleCity in cartPage.restaurants">{{ singleCity.city }}</option> </optgroup> </select> </div> </div> </div> <!-- if delete this everything is working! --> <div v-if="cartPage.pickup" class="delivery__col delivery__address"> <div class="delivery__col-heading">Address: <div class="custom-select__wrapper item__option delivery__address-city"> <select v-model="cartPage.currentCity" @change="setDefaultDistrict" class="custom-select"> <option v-for="singleCity in cartPage.restaurants" v-bind:value="singleCity" v-bind:selected="cartPage.currentCity.city == singleCity.city ? true : false">{{ singleCity.city }}</option> </select> </div> </div> <div class="delivery__row delivery__row-flex-start">District <div class="custom-select__wrapper item__option"> <select v-model="cartPage.currentDistrict" @change="setDefaultRestaurant" class="custom-select"> <option v-for="singleDistrict in cartPage.currentCity.districts" v-bind:value="singleDistrict">{{ singleDistrict.districtName }}</option> </select> </div> </div> <div class="delivery__row delivery__row-flex-start">Restaurant: <div class="custom-select__wrapper item__option"> <select v-model="cartPage.currentRestaurant" class="custom-select"> <option v-for="singleRestaurant in cartPage.currentDistrict.restaurants" v-bind:value="singleRestaurant">{{ singleRestaurant.placeName }}</option> </select> </div> </div> <div class="delivery__row delivery__row-flex-start delivery__row--last-row"><span v-if="cartPage.currentRestaurant" class="delivery__row-note">{{ cartPage.currentRestaurant.address }}, {{ cartPage.currentRestaurant.hours }} ч.</span></div> </div> </div> </div> </div> </div>
Vue route is not render data property of vue instance in vue js
I’m facing a problem in vue route. The problem is vue route is not render data property 'people' of vue js instance. Please guide me what is the problem here. Here is my code.
Console Error:
Property or method "people" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
and also my running code available here:JsFiddle Code
<body> <div id="vue-app"> <router-link to='/create'>Create employee</router-link> <!-- router outlet --> <router-view></router-view> </div> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script type="text/x-template" id="create_template"> <div> <div v-for="person in people "> <p v-text="person.name"></p> </div> <p>create display here </p> </div> </script> <script type="text/javascript"> const create_or_edit = { template: '#create_template' }; const routes = [ {path: '/create', component: create_or_edit,}, ]; const router = new VueRouter({ routes: routes, }); const app = new Vue({ router: router, data(){ return { people: [ {name: "Ali"}, {name: "Kamran"}, {name: "Qaiser"}, ], } } }).$mount('#vue-app') </script>How to update the values in vue.js?
I am in the need of edit and update the values using vue.js,
For which i have used the edit to get the values and i am able to edit but whereas i am unable to update .
Update Click button:
<span><button type="submit" @click="updateItems" name="add" class="btn btn-default hidden-sm" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Save"><i class="fa fa-floppy-o"></i><span class="hidden-sm hidden-xs"> Save</span></button></span>Script of Edit:
<script> import config from '../../../config'; export default { data(){ return{ items: [], itemsData:{ room_id : '', start_date : '', end_date : '', package_id : '', price : '', child_price : '', discount : '', discount_type : '', people : '', price_sup : '', fixed_sup : '', tax_id : '', taxes : '' }, errors: { } } }, created: function() { this.fetchRates(this.$route.params.id); }, methods:{ fetchRates(id){ axios.get(config.apiDomain+'/Rates/'+id+'/edit').then((response)=>this.itemsData = response.data); }, updateItems(e){ axios.put(config.apiDomain+'/Rates/'+this.$route.params.id, this.itemsData).then(response=>{ // this.this.itemsData = ""; this.$router.push('/admin/rates'); }).catch(error=>{ this.errors = error.response.data; }); } }, mounted() { axios.get(config.apiDomain+'/Rates').then((response)=>this.items = response.data); } } </script>Update Controller:
public function update(Request $request, $id) { echo $id; return 'hi'; $rows = Rates::findOrFail($id); $this->validate($request, [ 'room_id' => 'required', 'start_date' => 'required', 'end_date' => 'required', 'price' => 'required' ]); $input = $request->all(); $rows->fill($input)->save(); Session::flash('flash_message', 'Rates successfully Updated!'); }It was throwing the error as,
XMLHttpRequest cannot load http://localhost/booking/booking-api/public/Rates/1. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.and also,
Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at eval (RatesEdit.vue?5784:221)Kindly give me a better solution that solves my issue.. I am able to do edit but unable to update the edited values by clicking save button..
Vue TypeError: Cannot read property 'message' of undefined
I am new to Vue.js and i'm building a rather simplistic chat from a tutorial and I got this error:
TypeError: Cannot read property 'message' of undefined
I did set message as a prop but I can't understand why it's undefined.
chatMessage.vue
<template lang="html"> <div class="chat-message"> <p>{{ message.message }}</p> <small>{{ message.user }}</small> </div> </template> <script> export default { props: ['message'] } </script> <style lang="css"> .chat-message { padding: 1rem; } .chat-message > p{ margin-bottom: .5rem; } </style>app.js
require('./bootstrap'); window.Vue = require('vue'); Vue.component('example', require('./components/Example.vue')); Vue.component('chat-message', require('./components/ChatMessage.vue')); Vue.component('chat-log', require('./components/ChatLog.vue')); Vue.component('chat-composer', require('./components/ChatComposer.vue')); const app = new Vue({ el: '#app' });chat.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>chat!</title> <link rel="stylesheet" href="css/app.css"> </head> <body> <div id="app"> <h1>Chat Room</h1> <chat-message></chat-message> <chat-log></chat-log> <chat-composer v-on:messagesent="addMessage"></chat-composer> </div> <script src="js/app.js" charset="UTF-8"></script> </body> </html>Please note that vue is connected via Laravel, all is working fine, yet i'm getting this error which i'm trying to find out how or where would I define message.
Thanks, Bud
pass a variable inside an array to update that variable dynamically - in Vue.js
i'm trying to change variables dynamically so as not to use too many switch statements. i was hoping to do this:
this.variable1 = 2 this.variable2 = 3 var array1 = [this.variable1, this.variable2]and then later do
array1[0] = 25 array1[1] = 12 console.log(array1[0]) //would output 25 console.log(array1[1]) // would output 12of course it this is not what happens which is normal but how can i achieve that dynamically? There must be a way i'm sure.
How can I display modal in modal on vue component?
My view blade like this :
<a href="javascript:" class="btn btn-block btn-success" @click="modalShow('modal-data')"> Click here </a> <data-modal id="modal-data"></data-modal>If the button clicked, it will call dataModal component (In the form of modal)
dataModal component like this :
<template> <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <!-- modal content data --> <div class="modal-content modal-content-data"> <form id="form"> <div class="modal-body"> ... </div> ... <button type="submit" class="btn btn-success" @click="add"> Save </button> ... </form> </div> <!-- modal content success --> <div class="modal-content modal-content-success" style="display: none"> <div class="modal-body"> ... </div> </div> <!-- modal content failed --> <div class="modal-content modal-content-failed" style="display: none"> <div class="modal-body"> ... </div> </div> </div> </div> </template> <script> export default{ ... methods:{ add(event){ const data = { ... } this.$store.dispatch('add', data) .then((response) => { if(response == true) this.$parent.$options.methods.modalContent('#modal-data', '.modal-content-success') else this.$parent.$options.methods.modalContent('#modal-data', '.modal-content-failed') }) .catch(error => { console.log('error') }); } } } </script>If response = true then modal with class = modal-content-success will appear
If response = false then modal with class = modal-content-failed will appear
I want if response = false, modal with class = modal-content-data still showing. So modal with class = modal-content-failed appears in modal with class class = modal-content-data
How can I do that?
How to order that when response = false, modal with class = modal-content-data still appear?
Vuejs - How to render vnodes of child components when using slots
How does one render vnodes from a parent component of its child components. I have a render function that is looping through an array of children found in this.$slots.default. The aim is to wrap the children in li tags.
The problem is that the children components don't render and I get empty li tags. What am I missing here and where can the solution be found in the documentation. The Fiddle Can be found here And the embedded code is below.
// Parent component const MyParent = Vue.component('my-parent', { render: function(createElement) { var parentContent = createElement('h2', "These are Parent's Children:") var myChildren = this.$slots.default.map(function(child) { //console.log("Child: ", child) return createElement( 'li', child ) }) var content = [].concat(parentContent, myChildren) return createElement( 'div', {}, content ) } }); // Child Component const MyChild = Vue.component('my-child', { template: '<h3>I am a child</h3>' }); // Application Instance new Vue({ el: '#app', components: { MyParent, MyChild } }) <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <my-parent> <my-child></my-child> <my-child></my-child> </my-parent> </div>
Vue JS unable to display to DOM the returned data of method
Template html
<div class="item" v-for="n, index in teamRoster"> <span> {{ getFantasyScore(n.personId) }} </span> </div>Method
getFantasyScore(playerId) { if(playerId) { axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + playerId) .then( (response) => { if( response.status == 200 ) { console.log(response.data.total) return response.data.total; } }); } }I'm trying to display the returned data to DOM but it doesnt display anything. But when I try to console log the data is displays. How can I be able to display it. What am I missing?
Manully add csrf token With Slim ,Axios and ForData
I have a a modal that would submit a file without using an actual form, I am using FormData, so upload it to server. This will work if csrf token is disabled, my question is, how would I send the csrf token manually? I am using slim,axios and vuejs.
var formData = new FormData(); formData.append('fileme',file); axios.post(uyab.uploadUrl, formData,{ headers: { 'Content-Type': 'multipart/form-data', 'csrf_name': uyab.csrf_name, 'csrf_value': uyab.csrf_value, 'Accept': 'application/json', }, })But this will return error of failed csrf token
I created a function that would fetch csrf name and values from specific routes, and thus returning with correct values, the only problem is I dont know how to make it work in vuejs using spa approach
how to load a component dynamically in vue
i have two components direct_bus_travel_time_in_between_stops & direct_bus_travel_distance_in_between_stops to be loaded after <li v-for="stop in stop_name_arr">{{stop}}</li> has been executed completely .
Is there any way to append the components dynamically inside a function to load it when I want it to load ?
Accessing the DOM in the Vue Mounted function
How do I access an element from within the mounted function in a VueJS instance.
When I try the following, it tells me that the element is undefined. When I see the DOM it is there. Could this be a case where the element is not rendered before I try to reference it?
document.getElementsByName('transferDate_submit')[0].addEventListener("change",function(){});vuejs nuxtjs Error render client side dynamic component
On server-side this good worked. But in browser - I have message error
Pls help me
Thank you!
[Vue warn]: Unknown custom element: <testimonial-photo-inner>
I have just installed VueJS on my website and I'm getting tonnes of console errors like the one above. I am not trying to create any Vue components (yet) but my website does contain a number of custom HTML tags.
Does Vue treat any custom HTML tage (e.g. not one in the HTML spec) as something it needs to compile and will it always complain about tags it doesn't recognise?
Is it possible to switch theses warning off?
Please note: This is not a duplicate of Vue js unknown custom element
The user there is actually trying to create a Vue component.