Vuejs

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

Dynamic number of inputs

Sun, 2017-08-06 23:21

I have problem with dynamic number of radio input in array like that

Color:<br> <label><input type="radio" name="params[54]" value="21">Blue</label> <label><input type="radio" name="params[54]" value="38">Yellow</label> Size:<br> <label><input type="radio" name="params[12]" value="32">S</label> <label><input type="radio" name="params[12]" value="44">M</label> <label><input type="radio" name="params[12]" value="58">L</label>

It could not be only Color and Size and it shoud have more than two or three inputs. I use VueJS Component.

export default { data () { return { params: {} } }, methods:{ update: function(){ // here I want use params } } }

I need watch change input and get params object witch one are selected like:

{ 54: 21, 12: 44 }

I seriously don't know how can I do this. Any ideas?

Categories: Software

How to integrate Node.js running on different port with Vue.js running on a different port altogether?

Sun, 2017-08-06 21:45

I have a local Node.js server running on port 3000. I have another dev server for front end using webpack, running on 8080. Node is connected to MySQL server. I want to send data from my Node to front end. My project structure looks like this:-

SampleProject -> BackEnd -> FrontEnd

Should I use CORS node module? If not how should I send the data?

Categories: Software

Update component

Sun, 2017-08-06 15:45

I am missunderstanding how to update a component. So, here is the HTML :

<div id="app"> <form v-on:submit="submitForm"> <input type="text" id="txtSearch"> <input type="submit" value="go"> </form> <br><br> <user></user> </div>

And the JS :

let userComponent = { template: 'your name is : {{name}}<br>You are {{age}}' }; let vueApp = new Vue({ el: '#app', components: {'user': userComponent}, methods: { submitForm: function(e) { e.preventDefault(); let val = document.getElementById('txtSearch').value; alert('submitted : ' + val); // normally i do a search here : let result = mySearch(val); // but let's do the job with this : let result = {name: 'John', age: 27}; // so now, how to modify the <user> with this data result ? } } });

So, my aim is to create a template, and of course update his data. How to do this ? I created a jsfiddle for testing : https://jsfiddle.net/4w0kh30t/1/ Thanks for your help.

Categories: Software

Vue.js and Vue-Resource Status 404 on Delete HTTP Request with json-server

Sun, 2017-08-06 15:44

i'm working on a sandbox project using Vue.js, Vue-resource, Vuex and json-server. I succeed to use the GET request with Vue-resource to display all my Customers but when i'm trying to remove a selected customer, the console show me a 404 error.

Here the error

Error 404

Can you help me to resolve this issue please ? Thanks :D

Here my Vuex store :

import Vue from 'vue' import Api from '../../../lib/Api' export default{ state: { customers: [], profiles: [], }, actions: { getCustomers({commit}) { Vue.http.get(Api.getCustomersUrl(), {}).then((response) => { commit('loadCustomers', response.data); }) }, getCustomerProfile({commit}, id) { Vue.http.get(Api.getCustomerProfile(id), {}).then((response) => { commit('loadCustomerProfile', response.data); }) }, deleteCustomerProfile({commit}, id) { Vue.http.delete(Api.getCustomerProfile(id), {}).then((response) => { }, (response) => { console.log('erreur', response) }) }, removeAllProfile({commit}) { Vue.http.delete(Api.getCustomersUrl(), {}).then((response) => { }) } }, mutations: { loadCustomers(state, customers) { state.customers = customers }, loadCustomerProfile(state, profiles) { state.profiles = profiles }, removeCustomerProfile(state, profiles) { state.profiles = profiles }, removeAllCustomerProfile(state, customers) { state.customers = customers } }, }

Here my customers component :

<div class="customers-list"> <div class="customers-list__content"> <img :src="customer.photo" @click.self="selectProfile"> <p>{{customer.first_name}}</p> <p>{{customer.last_name}}</p> <p>{{customer.jobTitle}}</p> <p>{{customer.email}}</p> <p>{{customer.company}}</p> </div> </div> </div> </template> <script> export default{ props: ['customer'], methods:{ selectProfile() { this.$store.dispatch('getCustomerProfile', this.customer.id) console.log(this.customer.id); }, removeAll(){ this.$store.dispatch('removeAllProfile') } }, } </script>

Here my selected customer component :

<template> <div> <img :src="profile.photo"> <p>{{profile.first_name}}</p> <p>{{profile.last_name}}</p> <p>{{profile.jobTitle}}</p> <p>{{profile.email}}</p> <p>{{profile.company}}</p> <p>{{profile.id}}</p> <i class="fa fa-trash-o" aria-hidden="true" @click.self="deleteProfile"></i> </div> </template> <script> import {mapState} from 'vuex' export default{ props:['profile'], methods: { deleteProfile(){ this.$store.dispatch('deleteCustomerProfile', this.profile.id); console.log(this.profile.id); }, }, } </script>

And here my Homepage to display all my content with a v-for directive :

<div class="home"> <h1>Hello, world !</h1> <div class="home__forms"> <input type="text" v-model="firstname" placeholder="first name"> <input type="text" v-model="lastname" placeholder="last name"> <input type="text" v-model="jobTitle" placeholder="job"> <input type="text" v-model="email" placeholder="email"> <input type="text" v-model="company" placeholder="company"> <input type="text" v-model="photo" placeholder="photo"> <button @click="submit">Add</button> </div> <div class="customers"> <customers-list v-for="(customer, index) in customers" :customer="customer" :key="customer.id"></customers-list> </div> <profile v-for="(profile, index) in profiles" :profile="profile" :key="profile.id"></profile> </div> </template> <script> import {mapState} from 'vuex' import CustomersList from './CustomersList.vue' import Customer from './Customer.vue' export default{ components: { 'customers-list': CustomersList, 'profile': Customer, }, data() { return{ firstname: "", lastname:"", jobTitle:"", email: "", company: "", photo:"", error: false, } }, computed: mapState({ customers: state => state.test.customers, profiles: state => state.test.profiles, }), methods:{ submit(){ var self = this; if(this.email === "" || this.firstname === "" || this.lastname ==="" || this.jobTitle === "" || this.company === "" || this.company === "" || this.avatar === "") { this.error =true } else { this.$http.post(process.env.API_URL + '/customers', { first_name: this.firstname, last_name: this.lastname, jobTitle: this.jobTitle, email: this.email, photo: this.photo, company: this.company }).then((response) => { self.error = false }, () => { self.error = true }); console.log("submitted"); } } }, created(){ this.$store.dispatch('getCustomers') }, } </script>

Have a good day !

Categories: Software

Vue2+Foundation, Getting error in their integration

Sun, 2017-08-06 13:25

I am integrating Vue2 and Foundation-sites, I keep getting this error Refused to load the font 'https://sxt.cdn.skype.com/assets/fonts/SkypeAssets-Regular.woff' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Kindly Help!!

Categories: Software

VueJS v-for unwanted behaviour

Sun, 2017-08-06 06:51

I get this problem whenever I modify an array that is used to render a v-for list.

Let's say I've got a v-for list of three items:

<ul> <li v-for="item in items"></li> <ul></ul> <ul> <li>One</li> <!-- Has focus or a specific child component --> <li>Two</li> <li>Three</li> </ul>

Add a new item to the items array:

<ul> <li>New Item</li> <!-- Focuses on this item, the child component seems to be moved here --> <li>One</li> <li>Two</li> <li>Three</li> </ul>

The focus seems to move...

Please have a look at a fiddle that illustrates the problem https://jsfiddle.net/gu9wyctr/

I understand that there must be a good reason for this behaviour, but I need to manage it or avoid completely. Ideas?

Categories: Software

Getting .key from Firebase using VueFire

Sun, 2017-08-06 06:30

I am trying to get a single key from firebase nodes and I can't get any from the code I have right now. Here is my code:

let app = Firebase.initializeApp(config) let db = app.database() let bdRef = db.ref() export default { name: 'hello', firebase: { businesses: bdRef.orderByChild('.key').equalTo('306') } }

I get this error when doing this: validation.js?5c80:234 Uncaught Error: Query.orderByChild failed: First argument was an invalid path = ".key". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"

When I do this with my code:

businesses: bdRef.orderByChild('title').equalTo('Feather Animation Wood Carving Supplies')

It comes with this array:

0:Object .key:"3021" address:"Hello Avenue" city:"" description:"Wood carving tools and supplies. Please contact us by phone or internet." email:"hi@gmail.com" employees:"1"

How do I get the .key property?

Categories: Software

I am getting an error when I run git subtree push --prefix dist heroku master telling me to run git pull

Sun, 2017-08-06 06:05

I am trying to use this tutorial https://medium.com/@sagarjauhari/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 so that I only push the dist folder to heroku. I am using the following code:

"deploy": "git subtree push --prefix dist heroku master"

so when I am satisfied with my changes that i have made locally, i do the following.

npm run build git add -A git commit -m "message" git push npm run deploy

then i get an error message that reads:

! [rejected] a1869b5091eac1a50721d4c0cb8385f48338d8d9 -> master (non-fast-forward) error: failed to push some refs to 'https://git.heroku.com/foobar' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.

What am I doing wrong? If I run git push heroku at this point, it works fine.

Categories: Software

SPA on Laravel 5.4 and Vuejs2 - how to use middleware?

Sun, 2017-08-06 04:26

I'm developing SPA at first time. I't easy to use middleware in Laravel, but I have no Idea how to use it in Vuejs. I have 2 types of user and how can I give them an access to specific pages only? Unauthorized users should have access to home page only.

Categories: Software

no mousedown events on elements in quasar

Sun, 2017-08-06 03:59

My quasar version is 0.14, and I merage quasar to vue-cli and webpack template, so I change some vue-cli config, it works, but there is only one little problem, no showRipple effect when click elements, then I compare quasar-cli that has four events on element click,mousedown,mouseleve and mouseup, but my quasar element only has one event click, I do not know why and how to fix it, so help, thank you very much.

I show configs I changed for quasar, and github links

webpack.base.config.js

```

var path = require('path') var utils = require('./utils') var config = require('../config') var vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = { entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { // add for quasar quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'), src: path.resolve(__dirname, '../src'), assets: path.resolve(__dirname, '../src/assets'), '@': path.resolve(__dirname, '../src/components'), variables: path.resolve(__dirname, '../src/themes/quasar.variables.styl'), // end for quasar 'vue$': 'vue/dist/vue.esm.js', // '@': resolve('src') } }, module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] } }

```

index.html

```

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> <title>auto-activity</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>

```

package.json

```

{ "name": "auto-activity", "version": "1.0.0", "description": "A Vue.js project", "author": "shangwenlong652 <dxcqcv@gmail.com>", "private": true, "scripts": { "server": "node app.js", "migrate": "knex --knexfile=./server/config/knexfile.js migrate:latest", "rollback": "knex --knexfile=./server/config/knexfile.js migrate:rollback", "dev": "node build/dev-server.js", "start": "node build/dev-server.js", "build": "node build/build.js", "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run", "e2e": "node test/e2e/runner.js", "test": "npm run unit && npm run e2e", "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs" }, "dependencies": { "knex": "^0.13.0", "koa": "^2.3.0", "koa-bodyparser": "^4.2.0", "koa-jwt": "^3.2.2", "koa-logger": "^3.0.1", "koa-router": "^7.2.1", "mysql": "^2.13.0", "quasar-extras": "0.x", "quasar-framework": "git+https://git@github.com/quasarframework/quasar-edge.git", "objection": "^0.8.5", "vue": "^2.3.3", "vue-router": "^2.6.0" }, "devDependencies": { "autoprefixer": "^7.1.2", "babel-core": "^6.22.1", "babel-eslint": "^7.1.1", "babel-loader": "^7.1.1", "babel-plugin-istanbul": "^4.1.1", "babel-plugin-transform-runtime": "^6.22.0", "babel-preset-env": "^1.3.2", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.22.0", "chai": "^3.5.0", "chalk": "^2.0.1", "chromedriver": "^2.27.2", "connect-history-api-fallback": "^1.3.0", "copy-webpack-plugin": "^4.0.1", "cross-env": "^5.0.1", "cross-spawn": "^5.0.1", "css-loader": "^0.28.0", "cssnano": "^3.10.0", "eslint": "^3.19.0", "eslint-config-standard": "^6.2.1", "eslint-friendly-formatter": "^3.0.0", "eslint-loader": "^1.7.1", "eslint-plugin-html": "^3.0.0", "eslint-plugin-promise": "^3.4.0", "eslint-plugin-standard": "^2.0.1", "eventsource-polyfill": "^0.9.6", "express": "^4.14.1", "extract-text-webpack-plugin": "^2.0.0", "file-loader": "^0.11.1", "friendly-errors-webpack-plugin": "^1.1.3", "html-webpack-plugin": "^2.28.0", "http-proxy-middleware": "^0.17.3", "inject-loader": "^3.0.0", "karma": "^1.4.1", "karma-coverage": "^1.1.1", "karma-mocha": "^1.3.0", "karma-phantomjs-launcher": "^1.0.2", "karma-phantomjs-shim": "^1.4.0", "karma-sinon-chai": "^1.3.1", "karma-sourcemap-loader": "^0.3.7", "karma-spec-reporter": "0.0.31", "karma-webpack": "^2.0.2", "lolex": "^1.5.2", "mocha": "^3.2.0", "nightwatch": "^0.9.12", "opn": "^5.1.0", "optimize-css-assets-webpack-plugin": "^2.0.0", "ora": "^1.2.0", "phantomjs-prebuilt": "^2.1.14", "rimraf": "^2.6.0", "selenium-server": "^3.0.1", "semver": "^5.3.0", "shelljs": "^0.7.6", "sinon": "^2.1.0", "sinon-chai": "^2.8.0", "stylus": "^0.54.5", "stylus-loader": "^3.0.1", "url-loader": "^0.5.8", "vue-loader": "^12.1.0", "vue-style-loader": "^3.0.1", "vue-template-compiler": "^2.3.3", "webpack": "^2.6.1", "webpack-bundle-analyzer": "^2.2.1", "webpack-dev-middleware": "^1.10.0", "webpack-hot-middleware": "^2.18.0", "webpack-merge": "^4.1.0" }, "engines": { "node": ">= 4.0.0", "npm": ">= 3.0.0" }, "browserslist": [ "> 1%", "last 2 versions", "not ie <= 8" ] }

```

src/main.js

```

// const __THEME = 'mat' // === DEFAULT / CUSTOM STYLE === // WARNING! always comment out ONE of the two require() calls below. // 1. use next line to activate CUSTOM STYLE (./src/themes) // require(`./themes/app.${__THEME}.styl`) // 2. or, use next line to activate DEFAULT QUASAR STYLE // require(`quasar/dist/quasar.${__THEME}.css`) require(`quasar/dist/quasar.mat.css`) // ============================== // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Quasar from 'quasar' import App from './App' import router from './router' Vue.config.productionTip = false Vue.use(Quasar) import 'quasar-extras/roboto-font' import 'quasar-extras/material-icons' // import 'quasar-extras/ionicons' // import 'quasar-extras/fontawesome' import 'quasar-extras/animate' Quasar.start(() => { /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } }) })

```

test component,

```

<template> <q-layout ref="layout" view="lHh Lpr fff" > <q-toolbar slot="header" color="primary" > <q-toolbar-title class="row items-center"> <q-icon name="account balance" class="on-left" /> 运营活动快速搭建系统 <q-search inverted color="dark" placeholder="输入项目关键字" class="on-right" /> </q-toolbar-title> </q-toolbar> <q-btn icon="create">New item</q-btn> <q-list link separator > <q-list-header>已有项目列表</q-list-header> <q-item v-for="n in 3" :key="n"> <q-item-side icon="folder" inverted color="grey-6" /> <q-item-main> <q-item-tile label>抽奖项目 </q-item-tile> <q-item-tile sublabel>测试地址:test2-xxxxxx</q-item-tile> <q-item-tile sublabel>产线地址:q.yqb.-xxxxxx</q-item-tile> </q-item-main> <q-item-side right > <q-item-tile stamp >更新时间: {{updateDate}}</q-item-tile> </q-item-side> </q-item> </q-list> </q-layout> </template> <script> import { QLayout, QToolbar, QToolbarTitle, QIcon, QSearch, QList, QListHeader, QItem, QItemSeparator, QItemSide, QItemMain, QItemTile, date, QBtn, QField } from 'quasar' export default { name: 'index', components: { QLayout, QToolbar, QToolbarTitle, QIcon, QSearch, QList, QListHeader, QItem, QItemSeparator, QItemSide, QItemMain, QItemTile, QBtn, QField }, computed: { updateDate () { let timeStamp = new Date() let formattedString = date.formatDate(timeStamp, 'YYYY-MM-DD') return formattedString } } } </script>

```

Categories: Software

Allow third-party js to communicate to my vuejs app

Sun, 2017-08-06 02:55

I'm creating a vuejs app. And I want to add the ability for third-party non-vue js scripts to send commands or data to my app. For example

window.app = new Vue({}) app.setTitle = 'Hello'

Of course I want to expose only certain methods and triggers.

Categories: Software

HTML5 Client-side App Open File Dialog

Sun, 2017-08-06 02:23

Ok, so first, let me explain that I've researched this extensively and am completely aware of the security implications. This is a client-side app using JavaScript, Vue, and pure HTML5.

I use a hidden input type file to get the file dialog.

<input id="image-input" class="hidden" type="file" accept="image/*" @change="imageFileSelected"> <button type="button" title="Change Image" @click="openImage"><img src="icons/open-image.png"></button>

You can ignore the fact that I'm using Vue because these are just the native onclick and onchange events. The problem applies to HTML5 in general. The button triggers the hidden file input just fine in Firefox, Edge, and Chrome. However, I noticed a problem with the later two, which is that the onchange event is not fired when you select the same file twice.

I've already seen the millions of other topics suggesting value = null. That solution works perfectly fine, except for one small trivial detail. Firefox will remember the last file that you uploaded and automatically select it, hence adding this fix for Chrome and Edge, breaks that desirable functionality that's present in Firefox. The reason I want the dialog to remember the last file is because of the nature of app itself. I expect that users may want to work on one of the files and then decide to start over by reloading the same file again.

openImage() { var el = document.getElementById('image-input'); el.value = null; el.click(); },

Other apps that exhibit this same issue:

  1. http://blueimp.github.io/jQuery-File-Upload/
  2. https://rowanwins.github.io/vue-dropzone/dist/index.html
  3. https://fineuploader.com/demos.html

It seems nobody else is aware of this or else just doesn't care about whether their dialogs remember the last selected file. Regardless, does anyone know a way to fix this problem without breaking the Firefox functionality I find desirable?

Categories: Software

Are you able to use vue.js inside an ejs file?

Sat, 2017-08-05 23:47

Sorry guys I am new to node.js and was wondering whether we are allowed to use vue.js within an ejs file.

Categories: Software

How to refer laravel csrf field inside a vue template

Sat, 2017-08-05 16:38

I have a vue template that contains a form:

<form id="logout-form" :action="href" method="POST" style="display: none;"> {{ csrf_field() }} </form>

In laravel, forms must have a csrf_field() defined. But within a vue component, the statement {{ csrf_field() }} means that I have a method named csrf_field in my vue instance and I am calling it.

How do I add csrf_field under this circumstance?

Categories: Software

Share Vue variable across whole Laravel application

Sat, 2017-08-05 16:29

I am using a mixin to detect mobile users. Now I don't want to import this mixin into every single component where I need it, because this way I think it is probably running multiple times at the same time.

So I tried to do it like this (in app.js):

import DetectMobile from './mixins/DetectMobile.vue' const app = new Vue({ el: '#app', mixins: [ DetectMobile ], });

But that doesn't work, when I try to access one of the variables from the mixin within a component, I get undefined.

Categories: Software

Vue.js To add class active when click and remove the previous one

Sat, 2017-08-05 13:00

I want to achieve this active link on my div element here you can see the example that i want to do with my code

http://jsfiddle.net/fiddleyetu/9ff79/

$(function() { $( 'ul.nav li' ).on( 'click', function() { $( this ).parent().find( 'li.active' ).removeClass( 'active' ); $( this ).addClass( 'active' ); }); });

in here using vue.js i can't do the active link on my div elements

image 1

enter image description here

here is my code for the elements on which i have to do the links active

<div class="conversion"> <div class="file has-text-centered icon-active-color" v-on:click="activeiconc"> <img src="../imgs/png.png"/> <h4>.PNG</h4> </div> <div class="file has-text-centered" v-on:click="activeicon" v-bind:class="{ 'icon-active-color':activeiconc,}"> <img src="../imgs/pdf.png"/> <h4>.PDF</h4> </div> <div class="file has-text-centered" v-on:click="activeicon" v-bind:class="{ 'icon-active-color':activeiconc }"> <img src="../imgs/jpg.png"/> <h4>.JPG</h4> </div> <div class="file has-text-centered" v-on:click="activeicon" v-bind:class="{ 'icon-active-color':activeiconc }"> <img src="../imgs/psd.png"/> <h4>.PSD</h4> </div> </div>

js

export default { components: { MainLayout }, data: function(){ return { logo: false, color:false, list:true, grid:false, deletebtn:false, isImageModalActive: false, activerow: false, activeiconc:false, } }, methods:{ showgrid:function(){ this.grid = true; this.list = false; }, showlist:function(){ this.list ^=true; this.grid = false }, showLogo:function(){ this.logo ^= true; this.color = false; this.deletebtn ^= true; this.activerow ^= true }, showColor:function(){ this.color ^= true; this.logo = false; }, activeicon:function(){ this.activeiconc ^= true; } } }
Categories: Software

Vue js - Define prop as a specific type

Sat, 2017-08-05 12:10

I'm building a vuejs component which accepts a prop by the name of idFieldType

Now I want this prop to accept only a Number Type or a String Type

So I wrote it as follows

idFieldType: { Type: Function, default: function() { return Number; }, validator: function() { if(value == String || value == Number) { return true; } return false; } }

I also tried replacing the type to Object.

My question is how can I write a prop that accepts only specific types ?

Categories: Software

VueJs - DOM not updating on array mutation

Sat, 2017-08-05 11:23

I have a model in which I'm initializing an array on ajax success after the model is mounted

var self = this; $.getJSON("somejson.json", function (data) { var list = []; list = data.list.map(function (item) { return { id: item.id, text: item.text }; }); self.selectableItems = list; });

I have a click method on each of these items which removes the item from selectableItems

select: function (item) { this.selectableItems.pop(item); },

selectableItems renders correctly initially, but when I mutate the array, the dom isn't updating. Although the actual array is being modified correctly.

I verified this by having a computed property that returns the count of selectableItems. This count is updated correctly when the item is removed, but the dom still shows the item.

I also noticed that when I hard code the value of selectableItems in the ajax, everything works as expected!

self.selectableItems = [{ id: 1, text: "adsad"}];

I'm aware of the caveats of array mutation in vue. But I feel I'm missing something basic here, as I have just started exploring Vue. Can someone point out on what I'm missing?

Categories: Software

Dynamically append other component in Vue

Sat, 2017-08-05 09:56

I'm building a Chrome extension using Vue, and currently I'm trying to inject some HTML into a webpage. This is the App.vue file I've built so far:

<script> import $ from 'jquery'; import OtherComponent from './components/OtherComponent'; export default { name: 'app', components: { 'other-component': OtherComponent, }, mounted() { $('body').append('<div>{other-component}<div>'); }, }; </script>

Obviously, the line $('body').append('<div>{other-component}<div>'); won't append other-component. I'm aware that other-component is generally used in the <template> of App.vue, but I need to do it from the JavaScript. Is there a way to make this work?

Categories: Software

How to call function from router template?

Sat, 2017-08-05 08:52

I am doing very simple page with url's switching. In one of url I need to call @click methods. Here is my code:

const NotFound = { template: '<p>Page not found</p>' } const Home = { template: '<p>home page</p>' } const Faq = { template: '<p>Faq page</p>' } const Book = { template: ` <div> <button @click="foo()">test</button> </div> ` } const routes = [ {path: '/', component: Home}, {path: '/book', component: Book}, {path: '/faq', component: Faq} ] const router = new VueRouter({ routes // short for `routes: routes` }) new Vue({ el: '#app', router, data: { }, methods: { foo() { console.log("ffffff"); } } })

But I am getting error: Property or method "foo" is not defined on the instance but referenced during render.

Categories: Software

Pages