Software
How to add items in list on button click?
Could you please tell me how to add an item to list on button click. Here is my code
https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview
var AddTODO = Vue.extend({ template: '#add-todo', props: ['m'], data: function () { return { message: '' } }, methods: { addTodo: function () { console.log(this.message) console.log(this.m); //this.m =this.message; }, }, }); <template id="add-todo"> <div> <input type="text" v-model="m"> <button @click="addTodo">Add todo</button> </div> </template>is there any way to add items
Vue and Vuex are reacting to data change differently
I have a normalized tree data structure, like following:
{ ‘1’: { uid: ‘1’, value: null, children: [‘2’] }, 2’: { uid: ‘2’, value: ‘Child text’, children: [] } }Then I have a custom component that renders the first element and renders children recursively. The state tree is initialized with only the first element in the beginning, then during render, it generates new elements by using children array.
When generating the second element and adding it to the tree with Vue.set(state, uid, elem), Vuex is re-rendering the first element as well. If I don’t use Vuex, then it works as expected.
Please see what I’m doing wrong in the fiddle, it’s a small script, just change the use_vuex boolean variable to see with and without Vuex and see the console log in render function.
Thank you.
How to remove unnecessary classes from app.(hash).css
I'm using webpack to build my project (generated by vue-cli). I use bootstrap(only the css part, the js part is unnecessary for me) as the UI framework.
I'm using only a small percentage of classes defined by bootstrap, for example only alert and alert-warning (a bit exaggerated, in reality, I used about 3% bootstrap classes).
I want to know whether there is a loader or plugin to remove unnecessary classes when generating app.css?
Any vujs library for video calling? [on hold]
Any vujs library for video calling?
Data binding not available in other function
I'm trying to send a base64 encoded string to my server but the data binding I use is "" in the function to send it.
This is the code:
processFile: function(event) { var rawFile = event.target.files[0]; var reader = new FileReader(); reader.readAsDataURL(rawFile); reader.onload = function() { this.file = reader.result.split(',')[1]; }; },So this.file contains the base64 string but when I access it in another function it's returning ""
What am I doing wrong here?
Vuejs dependency collection
im reading source code of Vue.js
i cant understand this part in defineReactive function which turns a property into setter and getter.
my question is :
why would vue add 2 dependency when the property is an object?(see code below ,#1 and #2 are 2 different dependency)
const dep = new Dep() let childOb = !shallow && observe(val) Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { const value = getter ? getter.call(obj) : val if (Dep.target) { dep.depend()// #1 if (childOb) { childOb.dep.depend() //#2 } if (Array.isArray(value)) { dependArray(value) } } return value } }how to use watch function in vue js
could you please tell me how to use watch function in vue js .I tried to used but I got this error.
vue.js:485 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "m" found in ---> <AddTodo> <Root>https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview
I created different components and watch properties in the main component
var AddTODO = Vue.extend({ template: '#add-todo', props: ['m'], data: function () { return { message: '' } }, methods: { addTodo: function () { console.log(this.message) console.log(this.m); this.m =this.message; }, }, });When I try to add item I am getting this error. Step to reproduce this bug
- Type anything on input field and click on Add button
Select Combo doesn't remember request value with VueJS
I have just included VueJS in my HTML form. it's great.
Now, I made conditional enable / disable inputs, and it also works great.
But now, each time I submit the form, the form doesn't remember anymore the old value.
Here is my input ( it also has laravel variables ):
<select class="form-control" id="treeType" name="treeType" v-model="tree" v-on:change="treeType()" > <option value="0" @if ($setting->treeType == 0) selected @endif>{{ trans('laravel-tournaments::core.playoff') }} </option> <option value="1" @if ($setting->treeType == 1) selected @endif>{{ trans('laravel-tournaments::core.single_elimination') }} </option> </select>And here is my VueJS code:
new Vue({ el: '#app', data: { isPrelimDisabled: false, isGroupSizeDisabled: false, isAreasDisabled: false, hasPrelim:0, tree:1, }, methods: { prelim: function(){ if (this.hasPrelim == 0){ this.isGroupSizeDisabled = true; }else{ this.isGroupSizeDisabled = false; } }, treeType: function(){ if (this.tree == 0){ this.isPrelimDisabled = true; this.isAreaDisabled = true; }else{ this.isPrelimDisabled = false; this.isAreaDisabled = false; } } }, created() { this.prelim(); this.treeType(); } })What am I forgetting?
Why is Vue Js computed message not showing up in the DOM?
I'm trying to compute a message in a Vue instance so that it shows up in a h1 element - reversed, but it's not showing up. Any idea why?
new Vue({ el: '#comp-prop2', data: { message: 'Hello World...again!' }, computed: { reversedMessage() { return this.message.split('').reverse.join(''); } } }) <script src="https://unpkg.com/vue"></script> <div id="comp-prop2"> <h1> {{ reversedMessage }} </h1> </div>
Why index-of not working correctly in vuejs?
I make a custom component in Vue.js .In My component, I have a list which has a delete button.On click of a button, it deletes the row.If I click any row it deletes the last row because the index is always -1 why? here is my code https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview
methods: { deleteTodo:function (item) { console.log(item) var index = this.items.indexOf(item); this.items.splice(index, 1); } }below Whole code
var MyComponent = Vue.extend({ template:'#todo-template', props:['items'], computed: { upperCase: function () { return this.items.map(function (item) { return {name: item.name.toUpperCase(),complete:item.complete}; }) } }, methods: { deleteTodo:function (item) { console.log(item) var index = this.items.indexOf(item); this.items.splice(index, 1); } } }) Vue.component('my-component', MyComponent) var app = new Vue({ el: '#App', data: { message: '', items: [{ name: "test1", complete:true }, { name: "test2", complete:true }, { name: "test3", complete:true }] }, methods: { addTodo: function () { this.items.push({ name:this.message, complete:true }); this.message =''; }, }, computed: { totalCount:function () { return this.items.length; } } });ag grid not retrieving data when mounted with vue using axios
I have this strange case when trying to retrieve data from mongoDB using axios not showing on grid. It should be already successful given the data can already loaded into the view (already tested it), but it's nowhere inside beforeMount, mounted, or ready hook.
I already tried with
this.gridOptions.onGridReady = () => { this.gridOptions.api.setRowData(this.ticketData) }but only yields partial success (unreliable), here's a code snippet to show what I mean,
<template> <div class="ticketing"> <ag-grid-vue style="width: 100%; height: 350px;" class="ag-fresh" :gridOptions="gridOptions" > </ag-grid-vue> {{testData}} <!--testData can be loaded--> <input type="button" @click.prevent="showData" value="test"> </div> </template> <script> //import stuff //header and url stuff export default { //component stuff data () { return { gridOptions: null, ticketData: [], testData: [] // only for testing purpose } }, methods: { showData () { console.log('data shown') this.testData = this.ticketData // this is working } }, beforeMount () { var vm = this axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}}) .then(function (response) { vm.ticketData = response.data }) // this is working .catch(function (error) { console.log(error) }) this.gridOptions = {} this.gridOptions.rowData = this.ticketData // this is not working this.gridOptions.columnDefs = DummyData.columnDefs } // mount, ready also not working } </script>To be more specific, I still can't determine what really triggers onGridReady of ag-grid in conjunction with Vue component lifecycle, or in other words, how can I replace button to show testData above with reliable onGridReady/Vue component lifecycle event?
Why is Vue js Method not working from click event?
I'm learning how to use Vue and one of the methods in my practice code isn't working, any idea why?
When clicking 'Add name' an alert should pop up, but it doesn't.
new Vue({ el: '#array', data: { names: ['Jo', 'Joana', 'Joanna', 'Joan'] }, methods: { addName: function() { alert('Adding name'); } } }); <script src="https://unpkg.com/vue"></script> <div id="array"> <ul> <li v-for="name in names" v-text="name"> {{ names }} </li> </ul> </div> <input type="text"> <button v-on:click="addName">Add name</button>
Vue 2 custom component valus is always "undefined"
I'm trying to create a custom component in Vue.
This is the simplest component I could come up with and the value prop is ALWAYS undefined.
<template> <div> - {{ value }} - </div> </template> <script> export default { props: ['value'], mounted() { console.log(this.value); } } </script>Not doing anything special when I call it:
<el-text-group v-model="testVar"></el-text-group> {{ testVar }}The variable testVar shows fine, but the custom component shows nothing?
I've followed a bunch of tutorials and the official docs:
https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events
I'm using latest Vue 2.4.2. It seems to work fine with Vue 2.2.x.
I've actually had this issue months ago but thought I would wait to see if something got fixed. But testing again now and the issue is still there. No idea, seems very basic, not sure if there is some change on how to do this?
FILES:
app.js
var component = require('./components/App.vue'); component.router = Vue.router; new Vue(component).$mount('#app');App.vue
<template> <div> Hello <hr/> <test-cpt v-model="testVar"></test-cpt> </div> </template> <script> export default { data() { return { testVar: 'test' }; }, components: { testCpt: require('./TestCpt.vue') } } </script>TestCpt.vue
<template> <div> - {{ value }} - </div> </template> <script> export default { props: ['value'] } </script>How to structure vue.js app so I can access ajax request data from computed property on page load
I have the following code (below) that lets a user search data in an array. I want to replace the data property with data from an api and I don't know the proper way to structure a vue.js app so the methods have access to ajax data that is called on page load.
I know I use the axios library to call the data.
Vue.axios.get('https://jsonplaceholder.typicode.com/posts/1').then((response) => { console.log(response.data) })MY CODE
https://jsfiddle.net/bny191f7/1/
Vue.js code
new Vue({ el: '#app', data: { searchString: "", users: [{ //____________I want to replace this data with api data "name": "Bob" }, { "name": "Angel" }, { "name": "Whatever" } ] }, computed: { filterUsers: function() { //___________And insure this has access to it //___________so the app continues to work var users_array = this.users, searchString = this.searchString; if (!searchString) { return users_array; } searchString = searchString.trim().toLowerCase(); users_array = users_array.filter(function(item) { if (item.name.toLowerCase().indexOf(searchString) !== -1) { return item; } }) return users_array;; } } });HTML
<form id="app" v-cloak> <input type="text" v-model="searchString" placeholder="Enter your search terms" /> <ul> <li v-for="user in filterUsers"> <p>{{user.name}}</p> </li> </ul>Django Rest Framework and Graphene comparison
I want to develop a django application with Vue.js which needs JSON data. As a result of my research both Django Rest Framework (DRF) and Graphene will help me give me the JSON data I need. I am now incline to learn and use Graphene because:
- They say Graphql is better than REST API
- DRF is more than just giving JSON data so I think it could be too much to use DRF just for the JSON data for the Vue.js
- Graphene looks to have shorter learning curve than DRF
Are all my thoughts right? Please correct me
How to show items in list uppercase?
I am trying to make simple list example in vue (A TODO LIST).Here I am trying to add filter of Uppercase (In other words all letter are in capital ).But it show's me error
here is my code https://plnkr.co/edit/THtaYSnGkBp7BlMYcNUl?p=preview
var app = new Vue({ el: '#App', data: { message: '', items: [{ name: "test1" }, { name: "test2" }, { name: "test3" }] }, methods: { addTodo: function () { this.items.push({ name:this.message }); this.message =''; }, deleteTodo:function (item) { console.log(item) var index = this.items.indexOf(item); this.items.splice(index, 1); } }, computed: { upperCase: function () { return this.items.map(function (item) { return this.item.upperCase(); }) } } })Error: Error in render function: "TypeError: Cannot read property 'upperCase' of undefined"
**vue.js:572 TypeError: Cannot read property 'upperCase' of undefined at script.js:29 at Array.map (<anonymous>) at Vue$3.upperCase (script.js:28) at Watcher.get (vue.js:2883) at Watcher.evaluate (vue.js:2990) at Proxy.computedGetter (vue.js:3265) at Proxy.eval (eval at createFunction (vue.js:9818), <anonymous>:2:311) at Vue$3.Vue._render (vue.js:4123) at Vue$3.updateComponent (vue.js:2542) at Watcher.get (vue.js:2883)**Getting a Post 403 Forbidden with Spring Boot (VueJS and Axios Frontend)
I've been having an issue with CORS and I have tried everything I could find on Stack Overflow and basically anything that I found on Google and have had no luck.
So I have user authentication on my backend and I have a login page on my frontend. I hooked up the login page with Axios so I could make a post request and tried to login but I kept getting errors like "Preflight request" so I fixed that then I started getting the "Post 403 Forbidden" error.
It appeared like this:
POST http://localhost:8080/api/v1/login/ 403 (Forbidden)Even trying to login using Postman doesn't work so something is clearly wrong. Will be posting class files below
On my backend, I have a class called WebSecurityConfig which deals with all the CORS stuff:
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsServiceImpl userDetailsService; @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS"); } }; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); // TODO: lock down before deploying config.addAllowedHeader("*"); config.addExposedHeader(HttpHeaders.AUTHORIZATION); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().disable(); http .cors() .and() .csrf().disable().authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/h2/**").permitAll() .antMatchers(HttpMethod.POST, "/api/v1/login").permitAll() .anyRequest().authenticated() .and() // We filter the api/login requests .addFilterBefore(new JWTLoginFilter("/api/v1/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class); // And filter other requests to check the presence of JWT in header //.addFilterBefore(new JWTAuthenticationFilter(), // UsernamePasswordAuthenticationFilter.class); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // Create a default account auth.userDetailsService(userDetailsService); // auth.inMemoryAuthentication() // .withUser("admin") // .password("password") // .roles("ADMIN"); } }On our frontend which is written in VueJS and using Axios to make the call
<script> import { mapActions } from 'vuex'; import { required, username, minLength } from 'vuelidate/lib/validators'; export default { data() { return { form: { username: '', password: '' }, e1: true, response: '' } }, validations: { form: { username: { required }, password: { required } } }, methods: { ...mapActions({ setToken: 'setToken', setUser: 'setUser' }), login() { this.response = ''; let req = { "username": this.form.username, "password": this.form.password }; this.$http.post('/api/v1/login/', req) .then(response => { if (response.status === 200) { this.setToken(response.data.token); this.setUser(response.data.user); this.$router.push('/dashboard'); } else { this.response = response.data.error.message; } }, error => { console.log(error); this.response = 'Unable to connect to server.'; }); } } } </script>So when I debugged via Chrome's tools (Network), I noticed that the OPTIONS request goes through as shown below:
Here is a picture of the POST error:
Here is another class which handles the OPTIONS request (JWTLoginFilter as referenced in the WebSecurityConfig):
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter { public JWTLoginFilter(String url, AuthenticationManager authManager) { super(new AntPathRequestMatcher(url)); setAuthenticationManager(authManager); } @Override public Authentication attemptAuthentication( HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException { AccountCredentials creds = new ObjectMapper() .readValue(req.getInputStream(), AccountCredentials.class); if (CorsUtils.isPreFlightRequest(req)) { res.setStatus(HttpServletResponse.SC_OK); return null; } return getAuthenticationManager().authenticate( new UsernamePasswordAuthenticationToken( creds.getUsername(), creds.getPassword(), Collections.emptyList() ) ); } @Override protected void successfulAuthentication( HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { TokenAuthenticationService .addAuthentication(res, auth.getName()); } }Axios not loading data to vue
I am trying to load cytoscape graph using vue and axios. Anyway cant configure cytoscape so I tried first with axios and vue only. There is still problem with scope, but I can't figure where? What should I change? How to properly set vuew and axios.
app = new Vue({ el: '#app', data:{ projekt: null, cy: null, nodes: [], edges :[], }, created(){ }, methods:{ to: function(){ var vm = this; axios.get('/json' + window.location.pathname) .then(function (response) { vm.projekt = response.data }); }, dodajElement: function(){ this.to(); console.log(this.projekt); } }Vuejs sending multiple get requests
I am making a Vuejs post request when component is mounted (using Vuex actually), and it all looks good. But when I inspect the console under network tab, I see that the get request is actually sent to the backend multiple times when the page loads. Is this normal? This is my request (using axios)
// component calling Store action methods: { ...mapActions({ fetchItems: 'items/fetchCart' }), }, mounted(){ this.fetchItems(); }Now in Axios, this is the action sent to the backend
const actions = { fetchItems({commit}){ return axios.get('/api/items').then((response) => { // commit a mutation to set the items in the state commit('SET_ITEMS', response.data) }).catch((error) => { console.log(error) }) }, }So this fetches the items just fine and populates the store, but I see from the network tab of my browser that this request is actually sent multiple times (5 times), which kind of affects some of my other logic in the backend.
I am using Laravel5.4 as the backend BTW.
Parent-child communication in VueJS
I have two Vue components. The parent-component:
Vue.component('parent-component',{ methods: { test: function(){ alert('Option Selected'); } }, template: ` <div><slot></slot></div> ` });And the animals component:
Vue.component('animals',{ data: function(){ return { selected: '' } }, template: ` <select @change="selectionChanged" v-model="selected"> <slot></slot> </select> `, methods: { selectionChanged: function(){ this.$emit('optionselected', this.selected); } } });And here is my HTML:
<div id="app"> <parent-component @optionselected="test()"> <animals> <option>Aardvark</option> <option>Bear</option> <option>Cat</option> </animals> </parent-component> </div>I am trying to get the selected option from child component (animals) to the parent component (parent-component). I am emitting the optionselected event from the child, but it looks like the parent component is not responding to that event, I mean the method test() is not being called at all. What am I doing wrong here?
Here is the JSFiddle Demo