Software
Importing variable to vue file
I need import some variable to vue component file. I am doing it this way:
require('imports-loader?myVar=>{test:12345}!./my-com.vue');As result I get [Vue warn]: Error in render function: "ReferenceError: myVar is not defined"
I know about props, but I want pass namely a variable.
Here "my-com.vue":
<template> <div>...</div> </template> <script> console.log(myVar); // <--- here I get vue warn export default { props:['rows'], ... } </script>Where I am wrong?
How it possible to import a variable to vue component file?
Thanks in advance.
How to make the put, delete request in vue.js
I want to make the put, delete request with authorization header in vue.js. This is the request.
Put request:
PUT https://api.petbacker.com/v4/account/a20343be-6c9f-11e7-8c94-42010af001bb HTTP/1.1 User-Agent: Fiddler Host: api.petbacker.com Content-Length: 82
{ "accountInfo" :{ "email": "iwillverifyemail@petbacker.com" } }Delete request:
DELETE https://api.petbacker.com/v4/account/a20343be-6c9f-11e7-8c94-42010af001bb/logout HTTP/1.1 User-Agent: Fiddler Host: api.petbacker.com Content-Length: 82 Authorization: RA a20343be-6c9f-11e7-8c94-42010af001bb:86aaccf288b7e4dc7692e4030dc96ace3ac009d3
{ "accountInfo" :{ "email": "iwillverifyemail@petbacker.com" } }This is my code.
this.$http.put(url, accountInfo, {headers: {'Authorization': authHeader}}) .then((response) => { // if succeed }) .catch(e => { console.log(e) }) this.$http.delete(url, accountInfo, {headers: {'Authorization': authHeader}}) .then((response) => { // if succeed }) .catch(e => { console.log(e) })I'm not sure it is correct. Let me know if you can solve this problem.
In Vue cli project, where to place Laravel api app and how to call api in vue js?
vue app is inside : C:\xampp\htdocs\booking
Laravel api is inside : C:\xampp\htdocs\booking-api
FYI : vue app is working on http://localhost:8080
If the folder structure is like above, then app works fine i can call the api like this,
axios.get('http://localhost/booking-api/public/Rooms').then((response)=>this.items = response.data);But I want booking-api folder inside booking folder. If I place it and if I call the api like below,
axios.get('/booking-api/public/Rooms').then((response)=>this.items = response.data);It wont work and the console window is like this,
Request URL:http://localhost:8080/booking-api/public/Rooms Request Method:GET Status Code:404 Not FoundSo, how can I place api project inside vue app and how to call the api from vue.
vue webpack 2 autoprefixer for ie9+
Using Vue generated Vuecli with the webpack build. There's a lot of magic going on. What I can't figure out is how to generate the vendor prefixes needed for IE.
This was copied from github issue: https://github.com/vuejs-templates/webpack/issues/421#issuecomment-284322065
vue-loader.conf.js
var utils = require('./utils') var config = require('../config') var isProduction = process.env.NODE_ENV === 'production' module.exports = { loaders: utils.cssLoaders({ sourceMap: isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap, extract: isProduction }), postcss: [ require('postcss-import')(), require('autoprefixer')({ browsers: ['ie >= 9'] }) ] }Simple container component example
container/index.vue
<template> <div class="container"> <slot></slot> </div> </template> <script> import './index.scss' export default {} </script>container/index.scss
// this is aliased in webpack.base.conf @import "~styles/base-config"; .container { @include grid(); // this generates display:flex and border-box resets max-width: 100%; margin: 0 auto; }Expected inline output generated in the head, (but currently don't get -ms-flexbox or -webkit- prefixes )
<style> .container { -webkit-box-sizing: border-box; // not generated box-sizing: border-box; display: -webkit-box; // not generated display: -ms-flexbox; // not generated display: flex; max-width: 100%; margin: 0 auto; } </style>Related:
access data property vuejs2
here is a piece of my code:
$(function () { var vm = new Vue({ el: '#app', data: { myObject : { id: "", _class : "", contentType : "TEXT", textValue : "", }, selected_language : "ENGLISH", }I want to find a way to fill the textValue property with what is in selected_language. which mean that my object will look like:
myObject : { id: "", _class : "", contentType : "TEXT", textValue : "ENGLISH", }Thanks for your help in advance, I am quite stuck
Nuxt.js, nuxt-link -> nuxt-child
I have problem while working with nuxt js, for example when im working with vuejs webpack i have the following code and it works fine.
<div class="col span-1-of-2 navigation-terms"> <ul class="nav-terms"> <router-link :to ="{name: 'usering'}" tag = 'li' style="cursor:pointer;">Terms of use</router-link> <router-link :to ="{name: 'Conf'}" tag = 'li' style="cursor:pointer;">Confidentiality </router-link> </ul> </div> <div class="col span-1-of-2 display-terms"> <transition enter-class="" enter-active-class="animated fadeInRight" leave-class = '' leave-active-class = ''> <router-view> </router-view> </transition> </div>However when im trying to implement something similar in nuxt.js by using this code:
<template> <div class=""> <nuxt-link to='sub/sub1'>Press me </nuxt-link> <nuxt-link to='sub/sub2'>Press me2 </nuxt-link> <h1>THAT TEXT IS MEANT TO STAY HERE RIGHT?</h1> <nuxt-child/> <nuxt-child> </nuxt-child> </div> </template>It doesnt work, it redirects me to page that i need but it removes all the parent elements. Like in this case all the nuxt-links should stay there as well as the h1 text. So what am i doing wrong?
This is a full repo:https://github.com/StasB93R/nuxt-child
P.S i know i have nuxt-link/ plus opening and closing tags of the same sort, i just put 2 of them for the testing purposes I would highly appreciate any help
How can I call a statement or method after the loop complete on vue component?
My vue component like this :
<template> <div class="row"> <div class="col-md-3" v-for="item in items"> ... </div> </div> </template> <script> export default { ... computed: { items() { ... } }, ... } </script>If the loop complete, I want to call a statement or method
So the statement is executed when the loop completes
How can I do it?
How do I emit an event after dispatch in VueJS?
I have a parent component with a grid of rows and I am using vuex to pass data, as i add a new record I would want to open the newly added record in a modal window. I am emitting an event and opening the modal with the first record (index = 0). The problem is that, as it is an ajax call to add record using an vuex "action", the emit happens before the record is added. How can I wait till the record is added with event? or Is there a better way to do it?
Below is the code:
<!-- Grid Component --> <grid> <addrow @newrecordadded="openNewlyAddedRecord"></addrow> <gridrow v-for="row in rows" :key="row._id"></gridrow> </grid> computed: { rows(){ return this.$store.state.rows; } }, methods:{ openNewlyAddedRecord(){ this.openmodal(this.rows[0]) } }my store.js
state: { rows : [] }so in addrow component once the user clicks on submit form it dispatches to vuex
methods:{ onsubmit(){ this.$store.dispatch('addrow',this.newrow); this.$emit("newrecordadded"); } }actions.js
addrow({ commit,state }, payload){ var url = "/add"; Axios.post(url,payload) .then(function(response){ commit('addnewrow',response.data); }); }mutations.js
addnewrow(state,payload){ state.rows.unshift(payload); }Or alternatively can we pass a call back function to dispatch?
Calling cross domain requests from almost static site
I'm using vuejs and almost everything I do is on client-side, but for thing I need to call the server-side to check if URL exists or not.
I don't want to make these requests from browser, because that doesn't make sense to fetch different website from my scripts that will be more like calling any bad website without user knowing it in background, so I need to call cloud-function(gce) or aws lambda(since I don't want to host the site on server for it, since it has just one api call).
What would be the best way to accomplish it, I'm looking for something like website is www.webapp.com and cloud-function call on www.webapp.com/checkUrl
Initialize Vue app after Firebase auth state changed
I have a bit of a conundrum in my Vue/vuex/vue-router + Firebase app. The bootstrap code is supposed to initialize Firebase, as well as the signed in user (if any) in Vuex:
new Vue({ el: '#app', router, store, template: '<App/>', components: { App }, beforeCreate() { firebase.initializeApp(firebaseConfig) // Because the code below is async, the app gets created before user is returned... .auth().onAuthStateChanged(user => { this.$store.commit('syncAuthUser', user) // this executes too late... }) } })In my routes, I have
{ path: '/home', name: 'Home', component: Home, meta: { requiresAuth: true } }as well as
router.beforeEach((to, from, next) => { let authUser = store.getters.authUser // this is not set just yet... if (to.matched.some(record => record.meta.requiresAuth)) { if (!authUser) { next('signin') // /home will always hit here... } next() } else { next() } }) ProblemAs mentioned in the comments, the app gets the authenticated user too late. So, when you go to /home while logged in, the app will run the beforeEachcheck in the routes... And the user instance will not be available just yet, so it will think that you are not logged in, when in fact you are (it's clear from my computed properties that are properly updated a few moments later).
QuestionSo, how do I change my code, so that the Vue app gets initialized only after Firebase returns the user and after that user is passed to the Vuex store? Plese let me know if I am doing something completely wrong.
Attempts- I tried the "unsubscribe" approach; however, its problem is that the onAuthStateChanged would only be triggered once. So, if I put my crucial this.$store.commit('syncAuthUser', user) there, then that code would only execute when the app is created, and not when the user logs out for example.
- I also tried a better approach here. I did work for me, but I felt bad wrapping onAuthStateChanged in another Promise, for sure there must be a better way; plus, it seems wrong to place the auth user initialization login in the routes file.
How to use array reduce with condition in JavaScript?
So I have an array
const records = [ { value: 24, gender: "BOYS" }, { value: 42, gender: "BOYS" }, { value: 85, gender: "GIRLS" }, { value: 12, gender: "GIRLS" }, { value: 10, gender: "BOYS" } ]And I want to get the sum so I used the JavaScript array reduce function and got it right. Here is my code:
someFunction() { return records.reduce(function(sum, record){ return sum + record.value; }, 0); }With that code I get the value 173 which is correct. Now what I wanted to do is to get all the sum only to those objects who got a "BOYS" gender.
I tried something like
someFunction() { return records.reduce(function(sum, record){ if(record.gender == 'BOYS') return sum + record.value; }, 0); }But I get nothing. Am I missing something here? Any help would be much appreciated.
How do I use flask templating with Vuejs's “Mustache” syntax?
It seems there is some overlap.
For instance, this code:
<div id="entry"> <textarea rows="20" v-model="input"></textarea> <div> {{ input | md }} </div> </div> <script src="https://unpkg.com/vue@2.1.3/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script> <script> var vm = new Vue({ el: '#entry', data: { input: '' }, filters: { md: function(val){ return marked(val) } } }) </script>seems to work alright here: https://jsfiddle.net/5qvc815w/ (aside from the html tags rendered in the markdown)
but in flask I am getting
jinja2.exceptions.TemplateAssertionError TemplateAssertionError: no filter named 'md'it seems to be looking to jinja2 to discover whats in the curly braces instead of in vue.js which it should be doing.
Vuejs Local Directive Not Binding To Data When Passing A Method To Call
Defining a vuejs directive locally has issues when calling a method when being bound locally.
The problem: on tab/enter, look-up a value and set it based on what comes back (ie; setTimeout is the fake http call). Upon set time out completing, update the compute property.
I am aware of the migration docs says to use an 'eventHub' to communicate between the directive and the parent component. Is there another way to do this? If you check out the fiddle below, the global directive works perfectly while the local directive fails. I feel like the vm is not being bound properly on the local directive.
Local directive:
new Vue({ el: '#vue', directive: { localSomething: { bind (el, b, n, o) { $(el).on('keydown', function(e) { if(e.keyCode == 13 || e.keyCode == 9) { b.value($(el).val()); } }); } } }, ...Global directive:
Vue.directive('globalSomething', { bind (el, b, n, o) { $(el).on('keydown', function(e) { if(e.keyCode == 13 || e.keyCode == 9) { b.value($(el).val()); } }); } });Html:
Local: <input v-local-something="doSomething" /> Global: <input v-global-something="doSomething" />Method:
methods: { doSomething: function(value) { let vm = this; setTimeout(function() { vm.item.name = value; }); }Fiddle here: https://jsfiddle.net/4g1xyy9h/
Vuejs Tinymce - It's not working
Can you show me how can I run TinyMCE from VueJS2
I tried everything
I want to run it with this package https://www.npmjs.com/package/tinymce-vue-2 but i can't find out how to do it
thank you
Facebook Firebase Auth Error
I'm building a small app and want to authenticate it via Facebook. I have enabled Facebook as an auth method in the Firebase dashboard, provided my Facebook app tokens and the auth URI to Facebook.
This issue is this:
Uncaught TypeError: WEBPACK_IMPORTED_MODULE_0__firebase_config_js.a.FacebookAuthProvider is not a constructor
Here is the Vue JS Method in question:
const sphinx = firebaseApp.auth()
methods: { signUp (event) { sphinx.getRedirectResult().then(function (result) { if (result.credential) { var token = result.credential.accessToken } var user = result.user console.log(token, user) }) // Start a sign in process for an unauthenticated user. var provider = new sphinx.FacebookAuthProvider() sphinx.signInWithRedirect(provider) } }It seems to have something to do with the line:
var provider = new sphinx.FacebookAuthProvider()But I'm still fairly new to JS, but I think the issue is related to new in an ES6 environment? And if so, how can I change this.
How to pass Laravel data(json) to Vue component
I want to pass an Laravel object to my Vue component. In Vue I want to parse the data to an JSON object and I already tried this solution.
In my blade I have this:
<creator :object="parseData({{ $object->toJson() }})"></creator>And in my component I have this:
data() { return { ball: null } }, parseData(data) { this.object= JSON.parse(data); }This gives me the following error:
[Vue warn]: Property or method "parseData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
Can you tell me what I am doing wrong?
How to load others page's resources after login page complete loading
how to archive it and I use vue-cli to build my project. I have two ideas:1.change webpack config.2.use ''.Had someone archive it?
VueJS - manipulate DOM after computed
I'm getting posts and comments from an API, using Vuex. Right now, I have:
mounted () { this.$store.dispatch('getComments', this.post); }, computed: { comments () { return this.$store.getters.orderedComments; },The comments body is a string that contains HTML tags. I need to strip out the href attribute from a tags of a given class.
cleanUnwantedLinks () { const link = document.getElementsByClassName('link-class')[0]; link.removeAttribute('href'); }I'm not sure how to call cleanUnwantedLinks. It should be called just after the component is mounted (when I have the comments already). Is there a way to do it?
Is it possible to Import file in JS file using URL
I have little older version of vue.js ("vue": "^2.2.2") defined in package.json
Which I access in my JS like this:
import Vue from 'vue'But, I like to quickly test if things are working fine with newer version of vue.js.
import Vue from '//unpkg.com/vue@2.4.1'If not possible, any better ways?
How to handle anchors (bookmarks) with Vue Router?
I'm looking for a smart way to handle in-page anchors with Vue Router. Consider the following:
<router-link to="#app">Apply Now</router-link> <!-- some HTML markup in between... --> <div id="app">...</div>The "scroll to anchor" behavior described in the docs works fine except:
- When you click on the anchor, it brings you down to the div id="app". Now scroll away from the div back to the anchor and try clicking it again -- this time you will not jump down to the div. In fact, the anchor will retain the class router-link-active and the URL will still contain the hash /#app;
- With the steps above, if you refresh the page (the URL will still contain the hash) and click on the anchor, nothing will happen either.
This is very unfortunate from the UX perspective because a potential customer has to manually scroll all the way down to reach the application section.
I was wondering if Vue Router covers this situation. For reference, here's my router:
export default new VueRouter({ routes, mode: 'history', scrollBehavior(to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } else if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 } } } })