Display data in Vuejs - javascript

I need to display only name from request in my form, can't figure out how to do it. I'm just starting with js, need help.
I have tried this {{ request.name }} but doesn't work. {{request}} shows me full data.
const app = new Vue({
el:'#valuation-request',
data() {
return {
step:1,
request:{
name:null,
industry:'{{ $company->industry }}',
valuation_date:null,
similar_comp:null,
total_raised:null,
sales_transactions:null
}
}
},
methods:{
prev() {
this.step--;
},
next() {
this.step++;
}
}
});

If name has a value, it should display as you wrote it. If it's null, nothing will be displayed.
const app = new Vue({
el:'#valuation-request',
data() {
return {
step:1,
request:{
name: null,
industry:'{{ $company->industry }}',
valuation_date:null,
similar_comp:null,
total_raised:null,
sales_transactions:null
}
}
},
methods:{
prev() {
this.step--;
},
next() {
this.step++;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="valuation-request">
{{request.name}}
<hr>
Name: <input type="text" class="uk-input" name="name" v-model="request.name" id="name" placeholder="e.g. John Doe" required>
</div>

Related

How can I check if fields are empty on Send Message button?

<template>
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" v-model="firstName" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<input type="text" class="form-control" v-model="lastName" placeholder="Enter your last name">
</div>
<div class="form-group">
<label for="message">Type Your message</label>
<textarea class="form-control" v-model="message" rows="3"></textarea>
</div>
<div class="form-group form-check" v-for="number in numbers" :key="number">
<input type="checkbox" :value="number.Broj" v-model="checkedNumbers">
<label class="form-check-label" >{{number.Broj}}</label>
</div>
<button type="submit" class="btn btn-primary" v-on:click="alert" #click="sendMessage">Send message</button>
</div>
</template>
<script>
import http from "../http-common.js";
import userServices from "../services/userServices.js";
export default {
data()
{
return {
firstName: null,
lastName: null,
message: null,
numbers: "",
checkedNumbers: [],
success: 'You have submitted form successfully'
};
},
methods:
{
async sendMessage()
{
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers});
this.$data.firstName = "",
this.$data.lastName = "",
this.$data.checkedNumbers = [],
this.$data.message = "";
},
alert() {
alert(this.success)
if(event)
alert(event.target.tagName)
},
retrieveNumbers() {
userServices.getNumbers().then(response => {
this.numbers = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
created() {
this.retrieveNumbers();
}
}
</script>
So I want to add the option of checking input fields when user clicks "Send Message" button. I tried some options but I faield at that. So please I would appretiate if someone would help me. I'm still learning.
I know I have to use v-if and create the method for checking the fields.
So if you would be most kind and help me solve this problem I would be really grateful.
Thank you dev, community <3
Can I please get a concrete answer. Because I'll learn in that way, so please without condescending and "no-answers"
You can do it manually :
<script>
import http from "../http-common.js";
import userServices from "../services/userServices.js";
export default {
data()
{
return {
firstName: null,
lastName: null,
message: null,
numbers: "",
checkedNumbers: [],
success: 'You have submitted form successfully'
};
},
methods:
{
async sendMessage()
{
if(!(this.firstName && this.lastName && this.numbers)) return;
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers});
this.$data.firstName = "",
this.$data.lastName = "",
this.$data.checkedNumbers = [],
this.$data.message = "";
},
alert() {
alert(this.success)
if(event)
alert(event.target.tagName)
},
retrieveNumbers() {
userServices.getNumbers().then(response => {
this.numbers = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
created() {
this.retrieveNumbers();
}
}
</script>
Or you can this usefull library
https://vuelidate.js.org/#sub-basic-form
You can simply define a method to check the fields and call that before the HTTP request in the sendMessage method.
You can initialize your data as an empty string "" and have a method like this:
validateForm() {
return this.firstName != "" && this.lastName != "" && this.message != ""
}
Update your sendMessage method to something like this:
async sendMessage() {
const isFormValid = this.validateForm()
if (isFormValid) {
await http.post(....)
...
}
}

Reset component data on click (Without $vm.forceUpdate())

I have the following data in an application form component.
data() {
return {
manuallyEnterAddress: false,
currentAddress: "",
postcode: undefined,
postcode2: undefined,
address: {
county: "",
town: "",
addressLine1: "",
atAddressFrom: "",
atAddressTo: ""
},
}
}
Once the application for is completed the data will look similar to the code below.
data() {
return {
manuallyEnterAddress: true,
currentAddress: "Some House",
postcode: SK1MPS,
postcode2: SK5N0Q,
address: {
county: "Cheshire",
town: "Chester",
addressLine1: "Random street",
atAddressFrom: "01/01/91",
atAddressTo: "01/01/2010"
},
}
}
When the form has been completed the user needs a way to reset the application form, returning the the first stepper, with blank fields.
Manually writing each field to reset would be horrific as there's at least ten times the data.
I've tried forceUpdate as shown below with no success.
newApplication() {
$vm.forceUpdate()
}
Is there a way I could use the "newApplication" function to reset all of the data on the component?
In your case there is no need to re-render the vue Component, which is what forceUpdate() will be doing forcefully. I will suggest using an object for modeling your form, lets say, formModel. For Example:
Template:
<form id="app" #submit="checkForm" method="post" novalidate="true">
<label for="name">Name</label>
<input type="text" name="name" id="name" v-model="formModel.name">
<label for="email">Email</label>
<input type="email" name="email" id="email" v-model="formModel.email">
<input type="submit" value="Submit">
</form>
<<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
JS:
let app = new Vue({
el: "#app",
data: {
errors: [],
formModel: {}
},
methods: {
checkForm: function(e) {
let self = this
self.errors = []
if (!self.formModel.name) {
self.errors.push("Name required.")
}
if (!self.formModel.email) {
self.errors.push("Email required.")
} else if (!self.validEmail(self.formModel.email)) {
self.errors.push("Valid email required.")
}
if (!self.errors.length) {
self.initializeForm()
};
e.preventDefault()
},
validEmail: function(email) {
let re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/
return re.test(email)
},
initializeForm(){
self.formModel = {}
}
}
});
In this manner no matter how many input elements you have in your component you will just need to set the main model object.

can not change data in the #change vuejs handler

There is a component that contains input[type=file].
Also, this field has an uploadFile handler, which calls the validateMessage method, which attempts to change the error. As you can see, after changing this.error it shows that everything is correct. But in div.error it is not displayed and if you look in vueDevtool, then there is also empty.
data in vueDevTools
data() {
return {
error: ''
}
},
methods: {
validateFile(file) {
if (! file.type.includes('video/')) {
this.error = 'wrong format';
console.log(this.error); // wrong format
}
},
uploadFile(e) {
const file = e.target.files[0];
this.validateFile(file);
},
}
<input type="file"
id="im_video"
name="im_video"
#change="uploadFile"
class="hidden">
<div class="error">
{{ error }}
</div>
Here is working example.
new Vue({
el:'#app',
data() {
return {
error: ''
}
},
methods: {
validateFile(file) {
console.log(file.type);
if (! file.type.includes('video/')) {
this.error = 'wrong format';
//console.log(this.error); // wrong format
}
},
uploadFile(e) {
this.error = '';
const file = e.target.files[0];
this.validateFile(file);
},
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<input type="file"
id="im_video"
name="im_video"
#change="uploadFile"
class="hidden">
<div class="error">
{{ error }}
</div>
</div>
If you are using component this would help more to share data from child to parent in your case setting error from child component to parent
Vue.component('upload-file',{
template:`<div><input type="file"
id="im_video"
name="im_video"
#change="uploadFile"
class="hidden"></div>`,
data() {
return {
error: ''
}
},
methods: {
validateFile(file) {
//
if (! file.type.includes('video/')) {
vm.$emit('filerror', 'wrong format');
}
},
uploadFile(e) {
vm.$emit('filerror', '');
const file = e.target.files[0];
this.validateFile(file);
},
}
});
const vm = new Vue({
el:'#app',
mounted(){
this.$on('filerror', function (msg) {
this.error = msg;
})
},
data:{
error:''
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<upload-file></upload-file>
<div class="error">
{{ error }}
</div>
</div>

Vue component watch

all how i can watch changes in my component in data?
I need watch when user choose car brand to take from server models for that brand
this is my code
Templete
<template>
<div class="category-info">
<div v-for="input in inputs.text">
<label >{{ input.placeholder}}</label>
<input type="text" id="location" :name="input.name" v-model="input.value" #click="console">
</div>
<div class="select" v-for="select in inputs.select">
<label >{{ select.placeholder }}</label>
<my-select :data="select" v-model="select.value"></my-select>
</div>
<button #click="console">click</button>
</div>
Script
<script>
export default {
name: "profile-add-inputs",
props: ['category'],
data() {
return {
inputs: {
text : {},
select: {}
},
}
},
methods: {
getCategories(){
axios.get('/profile/inputs', {
params: {
category: JSON.stringify(this.category.href)
}
})
.then((response) => {
this.inputs.text = response.data.text;
this.inputs.select = response.data.select;
for(let key in this.inputs.text){
this.inputs.text[key].value = '';
}
for(let key in this.inputs.select){
this.inputs.select[key].value = '';
if(this.category.href.sub == 'car' && this.inputs.select[key].name == 'brand'){
console.log('CAR BREND');
this.$watch.inputs.select[key].value = function () {
console.log(this.inputs.select[key].value);
}
}
}
},this)
.catch(function (error) {
console.log(error);
});
},
console(){
console.log(this.inputs.select);
}
},
watch: {
category : function () {
this.getCategories();
console.log('categoty');
},
inputs : {
handler() {
console.log('watch inputs');
}
}
}
}
So, i tried to use watch and $watch but its not working, plz give me a reason why that not work, or maybe some another way to resolve this problem
this.$watch can i create dynamiclly watchers with this stement?
The correct syntax is
watch : {
inputs : function(val, oldVal){
//val : New value
//oldVal : Previous value.
}
}

Keeping track of added element in an array?

I'm playing around with vue.js and the .vue components, and as newbie, I'm wondering how can I keep track of the element I add in the array.
The situation is the following :
The user add a new element from a form
When he submit, the data are automatically added to a ul>li element, and a POST request is made to the API
When the POST is done, I want to update the specific li with the new data from the server.
The thing is, I can not target the last li because the server can take time to process the request (he do a lot of work), so the user may have added 1, 5, 10 other entries in the meantime.
So how can I do ?
Here's my code so far :
<template>
<form method="post" v-on:submit.prevent="search">
<input type="text" placeholder="Person name" required v-model="name" v-el="nameInput" />
<input type="text" placeholder="Company" required v-model="company" v-el="domainInput" />
<input type="submit" value="Search" class="btn show-m" />
</form>
<ul>
<li transition="expand" v-for="contact in contacts">
<img v-bind:src="contact.avatar_url" width="40px" height="40px" class="cl-avatar" />
<div class="cl-user">
<strong class="cl-name">{{contact.name}} <span class="cl-company">{{contact.company}}</span></strong>
</div>
</li>
</ul>
</template>
<script>
export default {
data () {
return {
contacts: [],
name: null,
company: null
}
},
methods: {
search: function (event) {
this.$http.post('/search', {
name: this.name,
company: this.company
}).then(function (xhr) {
// HERE ! How can I target the exact entry ?
this.contacts.unshift(xhr.data)
})
this.name = ''
this.company = ''
this.contacts.unshift({'name': this.name, 'company': this.company})
},
}
}
</script>
Thank you for your help ! :)
If you know that the name and company fields are unique you could search through the array to find it... otherwise you can just wait to append it to the array until the return function:
search: function (event) {
this.$http.post('/search', {
name: this.name,
company: this.company
}).then(function (xhr) {
this.contacts.unshift(xhr.data)
})
this.name = ''
this.company = ''
},
I finally found a working solution : I use a component instead of <li /> for each entries, and manage the state of these inside the component :
<ul>
<contact-entry v-for="contact in contacts" v-bind:contact="contact"></contact-entry>
</ul>
That way, when I add a new entry in the array (described above), a new instance of the component contact-entry is made.
Inside that component, I did the following :
<script>
export default {
props: ['contact'],
created: function () {
if (this.contact.id === undefined) { // If it's a new contact
this.$http.post('search/name', { // I do the post here
name: this.contact.name,
domain: this.contact.company.name
}).then(function (xhr) {
this.contact = xhr.data // This will update the data once the server has replied, without hassle to find the correct line
})
}
}
}
</script>
That's it ! :) In the parent's component, I removed the xhr request and simplified the method to :
<script>
export default {
data () {
return {
contacts: [],
name: null,
company: null
}
},
methods: {
search: function (event) {
this.name = ''
this.company = ''
this.contacts.unshift({'name': this.name, 'company': this.company})
}
}
}
</script>

Categories

Resources