Software
how to add filters and search in tables in vuejs?
I am learning vue js and building a SPA i want to know how do I add filters and search using an input tag. I also want to add a feature that when i click on a particular name on the table it should open the profile of that person also a select all functionality
<template> <div class="animated fadeIn"> <input type="text" placeholder="Enter Name" v-model="searchText"> <table class="table table-striped"> <thead> <tr> <th>Name</th> <th>College Name</th> <th>College City</th> <th>Level Name</th> <th>Submitted</th> <th>Pending</th> <th>Completed</th> <th>Approved</th> <th>Rejected</th> </tr> </thead> <tbody> <tr v-for="profile in profilesdata"> <td>{{profile.first_name}}</td> <td>{{profile.college_name}}</td> <td>{{profile.college_city}}</td> <td>{{profile.level_name}}</td> <td>{{profile.submitted}}</td> <td>{{profile.pending}}</td> <td>{{profile.complete}}</td> <td>{{profile.approve}}</td> <td>{{profile.rejected}}</td> </tr> </tbody> </table> </div> </template> <script> export default{ name: 'profiles', data () { return{ profilesdata: [] } }, created:function(){ this.loadlike() }, methods:{ loadlike:function(){ this.$http.get('/api/profiles').then(function (res) { this.profilesdata = res.body console.log(53+this.profiles) })}}} </script>How to load external script with same context as module doing the import?
I am trying to write an architecture that will allow people to add their own javascript without having to perform any build steps.
The context in this case is a dashboard UI, where each widget in the dashboard can be a plugin written by someone else.
The dashboard application is a VueJS-based app that is built by webpack and uses python on the backend. The idea is, using a tool like $script or some other script loader, the script that is loaded will have access to all the modules available in the UI. I expect to have Vue, axios, and D3 at the minimum. D3 especially is quite big so it'd be better not to force plugin authors to include their own copy of D3. The project is still in its infancy so Vue and webpack are not tools written in stone for me.
The only solution I can think up is defining a globally available function that calls a plugin function with dependencies as an argument, eg:
In the web app itself:
import * as d3 from 'd3'; import Vue from 'vue'; import axios from 'axios'; function plugin_loader(plugin_cb) { plugin_cb(d3, Vue, axios); }In a plugin:
plugin_loader(function(d3, Vue, axios) { // now the plugin can use those modules });But what I'm hoping is a possible solution, is simply for someone to write a plugin in a more "natural" way, using their own imports/requires() and using their bundler of choice to externalise away dependencies that the webapp already ships with.
So essentially, I want to include a third party js file at runtime, and that JS file can have access to all dependencies that the webapp itself has.
thanks in advance for any advice.
Can you implement Vue Unit tests without a component using purely the Vue Instance?
I briefly looked at the documentation on Vue Unit Testing
It said:
Anything compatible with a module-based build system will work
The documentation describes ways to test components
In my case I am not using a component. I am adding the vue.js to the page and I create a new Vue Instance.
new Vue({ el: '#app', data: { .... } });How to bind console.log to "l" in vue.js?
main.js has this code
window.l = function () { } try { window.l = console.log.bind(console) } catch (e) { }which works in non-Vue apps. However, when calling
l("test")from a Vue action/method, it complains it isn't defined.
How can that work?
Reasoning: need to output some debugging data, with as less typing as possible.
Vue JS Keep all imports in different file
Iam learning vuejs, i have hundreds of json file i want to load in to my Vue project , in my script, Simply i can do this loading all json files directly in main file as below
//Index.vue <script> import data1 from 'assets/json/data1.json'; import data2 from 'assets/json/data2.json'; ...above works fine, but now im planning to keep all imports into different file as below
//assets/imports.js import data1 from 'assets/json/data1.json'; import data2 from 'assets/json/data2.json';and refer imports.js as
//Index.vue <script> import alldata from 'assets/imports'is it possible to do like this, in not good in webpack too
How to call a function after element-ui table rows are rendered in Vue?
I have created a Vue component which contains a table from element-ui library. In a created() lifecycle hook, I am requesting table data and assigning the response as a table data.
What I need is to call a function after rows are rendered in a DOM. I have tried 3 approaches ...
1) nextTick() ... works bad
created() { this.isLoading = true; // Get all rows DataProvider.GetRows().then((returnedRowsData) => { this.tableData = returnedRowsData; this.isLoading = false; Vue.nextTick(() => { this.needToCallThisAfterTableDomIsCreated(); }); }); }2) mounted() lifecycle hook - works bad
mounted() { this.needToCallThisAfterTableDomIsCreated(); }3) Interval delay - this works, but is is not called immediately after table dom is rendered
created() { this.isLoading = true; // Get all rows DataProvider.GetRows().then((returnedRowsData) => { this.tableData = returnedRowsData; this.isLoading = false; setTimeout(() => { this.needToCallThisAfterTableDomIsCreated(); }, 2000); }); }How to access methods between components?
I have an application with two sibling components:
I would like, upon a specific action in Component1 to trigger a method in Component2. Is there a way to do this directly?
Currently, I use an over-engineered solution:
- upon the specific change in Component1, it $emit a signal to the parent
- ... who, through a handler, modifies a flag in its data
- ... which is passed as prop to Component2
- ... which watch this prop and triggers the appropriate method upon chnage.
This composition of flags, handlers and watchers is too complex so i am hoping for a more direct solution.
vue.js error : vue.common.js?e881:2888 'Uncaught TypeError: undefined is not iterable!'
In my vue project,I used vue-devtools. But when I clicked the 'vue' button,these is an error in console.I haven't any clue yet ,so I need some clue or solution, Please help me,Thank you very much if you can give me some help.
How to preload variables in a component style
So I successfully configure webpack for loading scss style that is in my components.
I use a <style lang="scss"></style> and it goes well.
But I would need to call some of my scss variables from there, so I guess I would need a kind of preload?
Is there a way to do it without having to @import in each component?
Stop referencing object with vuejs
I know that the default behaviour of a object when we create new atributes for the same instance is that it reference the old, changing the properties.
I have something like this on my vue data:
export default { data() { return { paragraph: { text: "", fontSize: 14, key: "Paragraph", align: "left" } } }, methods: { addParagraph() { this.$set(this.paragraph, 'key', this.paragraph.key); this.$set(this.paragraph, 'text', this.paragraph.text); this.$set(this.paragraph, 'fontSize', this.paragraph.fontSize); this.$set(this.paragraph, 'align', this.paragraph.align); this.$store.commit("appendToDocument", this.paragraph) }, alignment(option) { this.paragraph.align = option; } }everytime i click a button the data inside the paragraph changes and i want to pas the data to vuex store to add it to a json, so i can have a tree of paragraphs, the problem is, that everttime i create a new paragrapg it changes the values of my other paragraphs created before, is there a way to change it?
What's the use of webpack in vue CLI?
Ok, so I'm not being able to comprehend what value "webpack" gives in conext of Vue CLI.
I just installed vue cli globally.
then I made a directory manually and created a c1.vue file in it. With the template, script and style tags and related code.
and i compiled it using the command vue build --prod --lib c1.vue and it produced a c1.css and a c1.js file(s).
I simply add these files to my custom index.html file and use vue using a cdn and everything works !
So what's the point of webpack ?
Can I call a method from a watch and mounted?
I have a functionality (getAllData which does an external data query) which I need to call at two occasions: when the component is mounted and when a prop changes.
I am however getting a TypeError: this.getAllData is not a function when using it in a watch and in mounted.
Since methods can be called from methods, I am wondering whether this is true for methods being called from components such as watch or mounted.
My (simplified) instance is below:
export default { props: ['triggerReload'], data: function () { return { // some variables } }, watch: { triggerReload: this.getAllData() }, methods: { getAllData: function () { // this function correctly fetches external data } }, mounted: this.getAllData() }My workaround will be to either duplicate the code of the function (which is not DRY) or to call an external function (defined outside the Vue instance - which is probably also an anti-pattern) EDIT: this is a component so I do not know how to call an external function and reference the instance (it is not instantiated by var vm = new Vue(...))
Typescript emitted no output when running unit test
I have declared saveral variables in .d.ts files. It works right when running pack or build commands. But when I run unit test cases, things go wrong.
framework: vue+typescript+webpack
test runner: karma
I assume the problem is including .d.ts files is src, and I tried to exclude them. below is my regexp:
/\.\/(?!main\.ts)(?!((\S*\.d\.ts)|(\S*\.scss))$)/tested already, seems it doesn't work. keep throwing these exceptions. drvies me crazy.
anyone knows how to solve this issue?
How to test async method in Vuejs's component when using jest and avoriaz
For instance, I have a component looks like this.
<template> <div id="app"> <button class="my-btn" @click="increment">{{ val }}</button> </div> </template> <script> export default { data: { return { val: 1, }; }, methods: { increment() { fetch('/echo/html/').then((response) => { this.val++; }).catch((error) => { console.log(error); }); }, }, } </script>You can also check this fiddle as a simplified demo
In order to do unit test for this component, I wrote code like this.
// Jest used here test('should work', () => { // wrapper was generated by using avoriaz's mount API // `val` was 1 when mounted. expect(wrapper.data().val).toBe(1); // trigger click event for testing wrapper.find('.my-btn')[0].trigger('click'); // `val` should be 2 when the button clicked. // But how can I force jest to wait until `val` was set? expect(wrapper.data().val).toBe(2); });It didn't work since expect ran before fetch's done, but I've no idea how to let jest wait until promise function done.
So how can I test in this use case?
In Vue.js, POST method is not working using axios.post method
I am new to Vue.js. I am trying to create a simple login form, that will submit the values to a ASP.net Web API. When I click the submit button, I do not see the form data under POST. I am using Fiddler to check the POST data, which shows nothing under "WebForms" tab. On the ASP.net Web API the form object is shown as null. (For the sake of simplicity, I am passing hard code value to the post fields)
Following is the HTML inside login.vue
<template> <v-ons-page> <v-ons-toolbar> <div class="center">Log in </div> </v-ons-toolbar> <p style="text-align: center"> <img src="../assets/Image logo transparent.png" /> </p> <p style="text-align: center"> <v-ons-input modifier="underbar" placeholder="Username" type="text" v-model="user.name" float></v-ons-input> </p> <p style="text-align: center"> <v-ons-input modifier="underbar" type="password" placeholder="Password" v-model="user.password" float></v-ons-input> </p> <p style="text-align: center"> <v-ons-button @click="login($event)"> <div>Log in</div> </v-ons-button> </p> </v-ons-page> </template>Following is the section where POST happens through axios
<script> import axios from 'axios' export default { name: 'login', data: { username: '', password: '' }, computed: { user: { get () { return this.$store.state.user } } }, methods: { login (event) { axios.post('http://localhost:54977/api/Roles', { username: 'Fred', password: 'Flintstone'}) .then(response => { this.$ons.notification.alert('Logeed in. Hurrey!!') }) .catch(e => { this.$ons.notification.alert('No donut for you. :(') this.errors.push(e) }) } } } </script>How to correctly import css/styl files into a JavaScript file?
The file I want to import has this location: src/assets/css/global.styl.
I import it into vue files like this:
src/App.vue
<style lang="stylus"> @import './assets/css/global'I recently installed Storybook for Vue. I'm trying to import global.styl into the index.js file of Storybook for Vue:
src/stories/index.js
import '../assets/css/global.styl' // this works wine
However, I get this error:
ERROR in ./src/assets/css/global.styl Module not found: Error: Can't resolve './assets/img/buttons/radio-selected.svg' in 'E:\alex\vreditor\src\assets\css' @ ./src/assets/css/global.styl 7:12959-13009 @ ./src/stories/index.js @ ./.storybook/config.js @ multi ./~/@storybook/vue/dist/server/config/polyfills.js ./~/@storybook/vue/dist/server/config/globals.js (webpack)-hot-middleware/client.js?reload=true ./.storybook/config.jsWhy is this? and how to solve it?
NOTE: Seems like global.styl is being correctly imported. The problem are the relative paths inside the file:
input[type="radio"]:checked + label { &::before { background-image: url('./assets/img/buttons/radio-selected.svg') // Storybook can't find this. } }How can I disable back button on the browser with vue component?
My vue component like this :
<template> <span class="rating"> ... </span> </template> <script> export default { props: { 'star': null }, ... } </script>If the component is running I want to disable button back in the browser. So the user can not go back to the previous page
How can I do it?
Webpack with babel-loader not emitting valid es5
I have a webpack config that is based off https://github.com/vuejs-templates/webpack-simple/blob/master/template/webpack.config.js It uses vue-loader and babel-loader. The issue is I cannot get it to generate ES5 code so that it will work in the most broad range of clients.
If I use the ES2015 preset, webpack.optimize.UglifyJsPlugin fails to minify the output because Uglify can only handle ES5 (not counting the harmony branch). The errors are similar to: Unexpected token: punc (() and occur in multiple files.
I can work around this by using babili-webpack-plugin which will minify the ES6 code but is very slow. However, when I deploy this code, I see errors being reported back saying Block-scoped declarations (let, const, function, class) not yet supported outside strict mode so I know they are older clients choking on ES6 code.
How can I get proper ES5 code output from babel-loader? I have tried multiple presets, with or without the transform-runtime plugin. Config below:
const webpack = require('webpack'); const globEntries = require('webpack-glob-entries'); const _ = require('lodash'); const path = require('path'); const BabiliPlugin = require("babili-webpack-plugin"); const env = process.env.NODE_ENV; let entries; if (env === 'production') { entries = globEntries('./src/**/vue/*.js'); } else { entries = _.mapValues(globEntries('./src/**/vue/*.js'), entry => [entry, 'webpack-hot-middleware/client?reload=true']); } module.exports = { entry: entries, output: { path: '/', ///no real path is required, just pass "/" publicPath: '/vue', filename: '[name].js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { scss: 'vue-style-loader!css-loader!sass-loader', sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax', }, // other vue-loader options go here }, }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', query: { presets: ['es2015'], plugins: ['transform-runtime'], }, }, }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]', }, }, ], }, resolve: { alias: { vue$: 'vue/dist/vue.esm.js', }, }, plugins: [ new webpack.HotModuleReplacementPlugin(), // Enable HMR new webpack.NoEmitOnErrorsPlugin(), ], performance: { hints: false, }, devtool: '#eval-source-map', }; if (env === 'staging' || env === 'production') { //module.exports.devtool = env === 'staging' ? '#source-map' : false; module.exports.devtool = '#source-map'; module.exports.output.path = path.resolve(__dirname, './src/v1/parse/cloud/public/vue'); // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: `"${env}"`, }, }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false, }, }), // new BabiliPlugin(), new webpack.LoaderOptionsPlugin({ minimize: true, }), ]); }Vue.js data value not updating when adding new value
When new bars value are set, the data is not updated. Please check below;
I'm planning to do dynamic bars and buttons. Once the buttons are clicked, the new values will be updated to bars values.
Here is the link
HTML
<h1><span>Vue.js</span> Progress Bar</h1> <div id="app"> <div v-for="(index, bar) in bars" class="shell"> <div class="bar" :style="{ width: bar + '%' }" .> <span>{{ bar }}%</span> <input type="radio" id="radio-bar" value="{{ index }}" v-model="picked" v-on:change="set(index)"> </div> </div> <span v-for="(index, button) in buttons"> <button value="{{ button }}" @click.prevent="makeProgress(button)">{{ button }}</button> </span> <br> <p>Selected Bar: {{ picked }}</p> <p>Button Value: {{ buttonVal }}</p> </div>JS
var dataURL = 'http://pb-api.herokuapp.com/bars'; var vm = new Vue({ el: "#app", data: { maxColor: "#F22613", bars: [], buttons: [], limit: 0, selectedBar: 0, buttonVal: 0 }, methods: { fetchData: function(params) { this.$http.get(dataURL, function(data) { this.$set('bars', data.bars); this.$set('buttons', data.buttons); this.$set('limit', data.limit); console.log(params); }); }, set: function(index) { this.selectedBar = index; }, makeProgress: function(button) { var self = this; self.buttonVal += button; this.reachMax(); Vue.set(this.bars, 0, 55); }, reachMax() { if(this.buttonVal >= this.limit){ alert('Reached Limit' + this.limit) } } }, created: function() { this.fetchData(); } });axios set headers in config vue js
Right now I use axios like this:
import axios from 'axios' axios.get(apiObjUrl, { headers: { 'Content-type': 'application/x-www-form-urlencoded', } }) .then(({data}) => {How do I set global axios header? (I need to set localization header to use in all my requests)