Vuejs

Subscribe to Vuejs feed
most recent 30 from stackoverflow.com 2017-09-14T21:10:11Z
Updated: 7 years 1 week ago

How to turn FileReader image preview example into Vue component?

Thu, 2017-08-03 02:39

There's an example from MDN on how to use FileReader to show a preview image:

function handleFiles(files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var imageType = /^image\//; if (!imageType.test(file.type)) { continue; } var img = document.createElement("img"); img.classList.add("obj"); img.file = file; preview.appendChild(img); // Assuming that "preview" is the div output where the content will be displayed. var reader = new FileReader(); reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img); reader.readAsDataURL(file); } }

I'm wondering how to use this in a Vue component. It seems to me the asynchronous part isn't that easy to handle, but I'm new to Vue, and maybe that's an advanced feature.

Categories: Software

Overriding props before displaying

Thu, 2017-08-03 02:29

In Vue, is there a way to override/manipulate the props data before displaying it in the view by setting a method, or is there an switch or if which I can use inside the component template?

So basically, if the props is "hello", I want to display it like "Hello World."

What is the proper way of achieving this in vue?

Categories: Software

Component v for doesn't recognise prop, if not explicitly declared while initializing object in root

Thu, 2017-08-03 01:48

In my root, I am declaring my (multidimensinal) object in data like so:

var app = new Vue({ el: '#root', data: { accounts: {} }

If I send the props like this:

<div id="root"> <my-component :accounts="accounts"></my-component> </div>

Also in component, accept props. In the component, I also have the template that I perform a for loop.

Vue.component('my-component', { props: ['accounts'], template ` <div> <another-component v-for="(x, i) in accounts"></another-component> </div> ` })

In this case, where while I am initializing the accounts in the root, if I give it an empty object, it won't perform the loop.

If in for loop, instead of accounts, I use a digit, it performs the loop.

Also, while initializing in the root, if I become explicit...

accountTypes : { 1: [], 2: [] },

...the for loop works. However, this time I get another error:

Avoid using non-primitive value as key, use string/number value instead.

Also, I don't want to be explicit on 1 and 2, sometimes I don't want 2 to be there at all.

I am filling up accounts with a method in my root, binded to checkbox @change.

methods: { accountSelected() { this.pushValue(index, name) }, pushValue(key, value) { var obj = this.accounts if (obj.hasOwnProperty(key)) { var idx = $.inArray(value, obj[key]); if (idx == -1) { obj[key].push(value); } } else { obj[key] = [value]; } }, }
Categories: Software

Failed to mount component: template or render function not defined

Thu, 2017-08-03 01:24

I'm trying to build a very simple vue app that displays a modal. I'm using sweet-modal-vue. I am using webpack to bundle my app, primarily so that I can easily import sweet-modal-view into my app.

Something is breaking somewhere in the process and whenever I open my index.html file I get this error:

Failed to mount component: template or render function not defined. Found in <SweetModal>

After looking for a solution I found almost everyone who had this problem solved it by aliasing vue to the full compiler build, as described here. This did not work for me.

Any help would be greatly appreciated, I've been banging my head against this for hours.

Versions:

Vue: 2.8.2 sweet-modal-vue: 5.3.0 Webpack: 3.4.1

Here are the relevant files, let me know if you'd like to see more:

main.js:

import Vue from 'vue'; import App from './app.vue'; import { SweetModal, SweetModalTab } from 'sweet-modal-vue'; new Vue({ el: '#myapp', components: { SweetModal, SweetModalTab, App }, data: { message: "Hello Vue" }, methods: { openModal: function() { console.log(SweetModal); this.$refs.modal.open(); } } })

index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vue Example</title> </head> <body> <div id="myapp"> <app></app> <h3>{{ message }}</h3> <sweet-modal ref="modal" icon="success"> This is a success!! </sweet-modal> Accurate <button v-on:click="openModal()">Modal</button> </div> </body> <script src="dist/build.js"></script> </html>

webpack.config.js

module.exports = { // This is the "main" file which should include all other modules context: __dirname, entry: __dirname + '/src/main.js', // Where should the compiled file go? output: { // To the `dist` folder path: __dirname + '/dist', publicPath: 'dist/', // With the filename `build.js` so it's dist/build.js filename: 'build.js' }, module: { // Special compilation rules rules: [ { // I tried this option as well, it didn't help // test: /\.vue$/, // loader: 'vue-loader', // options: { // loaders: { // // {{#sass}} // // Since sass-loader (weirdly) has SCSS as its default parse mode, we map // // the "scss" and "sass" values for the lang attribute to the right configs here. // // other preprocessors should work out of the box, no loader config like this necessary. // 'scss': 'vue-style-loader!css-loader!sass-loader', // 'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax' // // {{/sass}} // } // // other vue-loader options go here // } test: /\.vue$/, loader: 'vue-loader', options: { loaders: { // Customize to your liking js: 'babel-loader', scss: [ 'style-loader', 'css-loader', 'sass-loader' ] } } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {'vue$': 'vue/dist/vue.esm.js'} } }
Categories: Software

Vue is not defined C9

Thu, 2017-08-03 00:55

Hey guys I am trying to get vue.js up and running for C9 but I wasn't able to find good resources for how to run it. When I try to run this app I get a Reference Error "Vue is not defined" Here is my index.html:

<!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <link href = "styles.css" rel = "stylesheet"/> <title>VueJS tutorials</title> <script src="https://unpkg.com/vue"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script> </head> <body> <div id = "vue-app"> <h1>{{name}}</h1> </div> <script src = "app.js"></script> </body> </html>

And here is the part where I am getting the error in app.js:

new Vue({ el:'vue-app', data:{ name:'Michael' } });

I am currently watching net ninja's tutorial and I am not sure how to fix this error.

Categories: Software

Vue2.0 unaccessible variable

Thu, 2017-08-03 00:48

I've am new at Vue and i've got a problem with unaccessible. I've got two files.

1st is App.vue where is defined <router-view>

<script> export default { name: 'app', data(){ return{ info: false, } }, beforeMount(){ example... this.info= true } } </script>

2nd is component Main.vue which is clear:

<script> export default{ name: 'main', data(){ return{ } }, beforeMount(){ //what i want to do: console.log(App.data().info) //here should be visible true in console log } }

i would like to have accessible in 2nd file the property from file number one. How to do it properly? Thank you in advance

Categories: Software

Is there any way to have multiple Vues have a computed listener working on the same value?

Wed, 2017-08-02 23:59

Setup:

I have multiple Vue components, and each component has multiple instances in different dialogs in my web app.

For each type of component I have a global state so that each type of component stays in sync across the dialogs.

I'd like for it so that when a component proceeds beyond step 1, I hide the other components in that dialog.

I have achieved this nicely using the computed / watch combo.

However, my problem is that it seems if I try to listen in with computed through more than 1 Vue instance, it hijacks the other listeners.

Problem

Below is a simplified version of what I'm working with, when the app starts up, the console logs 'computed 1' & 'computed 2'. But then when I change handrailOptions.step, only the second fires. ('computed 2' & 'watched 2')

Is there any way to have multiple Vues have a computed listener working on the same value?

var checkoutDialog = new Vue({ el: '#dialog-checkout', computed: { newHandrailStep() { console.log('computed 1'); return handrailOptions.step; } }, watch: { newHandrailStep( test ) { console.log('watched 1'); } } }); new Vue({ el: '#dialog-estimate-questions', computed: { newHandrailStep() { console.log('computed 2'); return handrailOptions.step; } }, watch: { newHandrailStep( test ) { console.log('watched 2'); } } });
Categories: Software

how to route dynamically in store.js file in vue

Wed, 2017-08-02 20:12

I have a function in store.js (vuex), that check some conditions, if satisfies, it should initiate route to another component.

this.$router.push() is not working in store.js .

Neither vm.$router.push() is working ,here vm = new Vue() .

Categories: Software

Websocket onmessage event doesnt update component data

Wed, 2017-08-02 19:32

I am setting my callbacks in mounted:

data() { return { code: 'Apple', } }, mounted() { console.log(this.code) // prints 'Apple' this.$options.sockets.onopen = this.wsOpen(); this.$options.sockets.onmessage = this.logMessage(msg); }, methods: { logMessage(msg){ this.code += "\n" + msg.data; console.log("this.code: " + this.code); }, }

However it is telling me that 'msg' is not defined. The following works, however this.code becomes out of scope:

this.$options.sockets.onmessage= function (msg) { console.log(msg.data) // this works, msg is not undefined here console.log(this.code) // doesnt work, this.code is undefined }

I think im doing something dumb.

Categories: Software

Pass a variable in an array, not a value in javascript

Wed, 2017-08-02 18:50

is there a way to pass a variable itself, not a value in javascript? I remember being able to do so in flas as3 if i remember correct which was based on javascript. I'm not sure why i can't do the same here. Your help would be much appreciated.

variable1: false, function1() { this.variable1 = true //this works of course console.log(this.variable1) prints true } function2() { var temparray1 = [this.variable1] temparray1[0] = true //does not work like i want, it's the value in the array that change, not this.variable1 console.log(this.variable1) //prints still false console.log(temparray1[0]) //prints true }
Categories: Software

Vue js data attribute not updating after click event?

Wed, 2017-08-02 18:42

I've created a vue component for a sorting icon, for tables etc.

The idea being a user can click on the icon to change the sorting (A->Z , Z->A)

<template> <i class="mdi mdi-sort" aria-hidden="true" @click.prevent="sort()" :class="{active: (active == name), desc: (orderDir == 'DESC')}"> </i> </template> <script> export default { props: { name: { required: true }, active: { required: false, }, eventName: { required: true, } }, data() { return { orderDir: "DESC", } }, methods: { /** * Fire a sort event with details of the field name and the direction to be sorted */ sort() { console.log(this.orderDir); if (this.orderDir === "DESC") { this.orderDir = "ASC"; } else { this.orderDir = "DESC"; } console.log(this.orderDir); EventBus.fire(this.eventName, { "name": this.name, "direction": this.orderDir }); } }, } </script>

The issue is with the sort() method, which during execution does not seem to update the orderDir property.

Console Output

------ First click

DESC

ASC

------ Second click

DESC

ASC

The expectation is that second time around the orderDir value should be already set to "ASC" and would be reverted back to "DESC".

I think I am missing out something obvious?

Categories: Software

VueJS nested component doesn't update property on action

Wed, 2017-08-02 17:51

This example of the official guide works properly (of course).

Then I tried by my own by making it a component, it also works.

But once nested in a parent component, the message can not be reversed, and I can't figure out why.

Vue.component('todo-item', { props: ['todo'], template: '<div>' + '<li>{{ todo.text }}</li>' + '<button v-on:click="reverseMessage">Reverse Message</button>' + '</div>', methods: { reverseMessage: function () { var reversed = this.todo.text.split('').reverse().join(''); console.log('tried with ' + reversed); this.todo.text = reversed; } } });

Here is the JSFiddle : https://jsfiddle.net/37y1ukjh/

Categories: Software

How to structure a multi-page website with Vue on each page

Wed, 2017-08-02 17:18

I'm trying to use Vue on my first multi-page website and don't know how to split my code across pages. Let's say I have a "master" template which contains the headers and footer + 3 pages, Home, About and Contact.

If I have a single Vue instance in the master template I think I will need to have all the code for every page in that instance.

If I have a separate instance for each page then what do I do about shared code, e.g. a button in the header which launches a popup?

I can't really use Vue components with their own templates because all the pages have to have their HTML on page when it loads for SEO reasons (using asp.enet Umbraco CMS)

Categories: Software

$router redefine and Vue.use(Vuex) should be called only once

Wed, 2017-08-02 17:07

My project created by webpack template!!;

npm run build online it can work well, but the vendor.js is too big!

modified webpack config webpack.prod.conf.js add this:

js externals: { 'vue': 'Vue', 'vee-router': 'VueRouter', 'vuex': 'Vuex', },

i separated the vue,vue-router,vuex , include by CDN ! like:

```html

<body> <div id="app"></div> <!-- built files will be auto injected --> <script src="https://unpkg.com/vue@2.3.4/dist/vue.js"></script> <script src="https://unpkg.com/vue-router@2.3.1/dist/vue-router.js"></script> <script src="https://unpkg.com/vuex@2.3.1"></script> </body>

```

but when i upload the file to line, some problems like:

vuex@2.3.1:667 [vuex] already installed. Vue.use(Vuex) should be called only once. vendor.js:24 Uncaught TypeError: Cannot redefine property: $router at Function.defineProperty () at Function.v [as install] (vendor.js:24) at Function.Vue.use (vue.js:4110) at Object. (vendor.js:24) at r (manifest.js:1) at Object. (app.js:1) at r (manifest.js:1) at Object. (app.js:1) at r (manifest.js:1) at Object. (app.js:1)

can someone help me?

Categories: Software

Set a boolean from buttonGroup (vue-strap)

Wed, 2017-08-02 16:53

I try to use the component buttonGroup from the library vue-strap as a toggle but I can't get it work. I succeed to set string value but not boolean value.

Here is the code

<button-group v-model="radioValue" type="primary"> <radio selected-value="true">Correct</radio> <radio selected-value="false">Incorrect</radio> </button-group>

The variable radioValue is updated correctly and set to "true" or "false" (string). But now I'd like to set a boolean instead (true or false).

I tried to make a codepen but I can't get it work neither. If it was working, I would tell you to open the console and execute vm.radioValue, click on Incorrect and execute vm.radioValue a second time. You will see that a string is set instead of a boolean.

I tried to bind the value (:select-value="true"). It kind of work but when the user clic on "Correct", the other button (Incorrect) is also active. Maybe it's a bug from vue-strap...

Categories: Software

Read Json file from <input> in front end [on hold]

Wed, 2017-08-02 16:34

I want to read a file got from an <input> on the front end, in order to parse it (it will be a json file). Im working on a webpack application using javascript with vue.js.

I've tried readFile or rawFile objects but it did't worked...

What can i do please ?

Thx.

Categories: Software

how to change page title according to route links vuejs

Wed, 2017-08-02 15:45

I want to change my page title according to the links I follow, just like how every page on stack overflow all have different page title with different links, some page titles are binded with the question title, how can such be done with vuejs, this will be good for search engine optimization, etc. I'm loving vuejs but I dont understand this part, is there something I'm missing?

Categories: Software

Updating a chart from chart.js in vue

Wed, 2017-08-02 15:39

I have a function in my vue applications that creates a chart.This is the chart function:

startChart: function (canvas, type) { // init chart.js var ctx = document.getElementById("myChart"); var myDoughnut = new Chart(ctx, { type: 'doughnut', data: { labels: this.getAnalyticList[this.getRowIndex].chartNames, datasets: [{ data: this.getAnalyticList[this.getRowIndex].chartData, backgroundColor: [ 'rgba(255, 99, 132, 0.6)', 'rgba(54, 162, 235, 0.6)', 'rgba(255, 206, 86, 0.6)', 'rgba(75, 192, 192, 0.6)', 'rgba(153, 102, 255, 0.6)', 'red', 'yellow', 'blue', 'green', 'orange', 'teal', 'violet', 'pink', 'purple' ] }] }, options: { responsive: true, defaultFontColor: '#ffffff', } }) }

and i then started it in the vue mounted hook using this line

this.startChart(this.$refs.canvas, 'Doughnut');

What i want to do is take the row index of a table loaded above the chart and that would then be passed into the getAnalyticList value that loads the charts so i can grab different arrays from the same list. I was working on creating an update function i got off this js fiddle from this stack article. I've been trying to adapt the function he created into vue but am having no luck here is the function:

changeData: function () { var myChart = Chart.doughnut(this.$refs.canvas, { data: data, }); myChart.data.datasets.data = this.getAnalyticList[this.getRowIndex].chartData; myChart.data.labels = this.getAnalyticList[this.getRowIndex].chartNames; myChart.update(); }

Any suggestions would be appreciated.

Categories: Software

Vue scope: how to delay handling of @mouseover

Wed, 2017-08-02 15:38

So I want to have an action only if the user has the mouse on the div for at least 1 second. Inside template:

<div @mouseover="trigger"></div>

Inside script:

data() { return { hovered: false } } methods: { trigger() { setTimeout(function(){ this.hovered = true }, 1000) } }

My problem is that I don't understand the scope of Vue. Because this.hovered is inside another function, it does not find the actual hovered data variable. What's the solution to this?

Categories: Software

How can I re-run Vue.js ApolloClient middleware?

Wed, 2017-08-02 15:07

In my main.js I have some code that checks for the existence of a localStorage item. If it has it, it will add an Authorization header via middleware to the ApolloClient setup.

However, if a localStorage item is later added, it's not present in the middleware of main.js. A full page refresh is therefore required in order to get it to pick it up / know of its existence.

How can I run main.js again (if that's even the solution) from a method in say, a component that signs the user in?

Here's my main.js:

import Vue from 'vue' import ApolloClient, { createNetworkInterface } from 'apollo-client' import VueApollo from 'vue-apollo' import App from './App' import router from './router' import store from './store' const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/MY-ID-HERE' }) const requestToken = localStorage.getItem('TOKEN') networkInterface.use([{ applyMiddleware (req, next) { if (!req.options.headers) { req.options.headers = {} } req.options.headers['Authorization'] = requestToken ? `Bearer ${requestToken}` : null next() } }]) const apolloClient = new ApolloClient({ networkInterface }) const apolloProvider = new VueApollo({ defaultClient: apolloClient }) Vue.use(VueApollo) /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App />', components: { App }, apolloProvider, router, store })

Hopefully you can understand what I'm trying to do?

Thanks

Categories: Software

Pages