V-model binding to generated input text field - vue.js

Dynamic V-models created during an ajax request doesn't update when I try inputting a value
I'm using vue2.x and axios. I want to get the value set in generated input when user submit the form. I managed to set v-model on this input during ajax request
I receive this HTLM as response:
<input type="text" value="" v-model="generatedcode">. But after submitting the form the value is still empty. Looks like Vue ignore the v-model directive. How can I fix it ?
Here is my code :
VUE
var app = new Vue({
el: '#subcribtionform',
data: {
generatedform:'',
generatedcode:''
},
methods:{
OnSuccess(response){
this.generatedform = response.data;
},
OnclickSub(){
axios.post('/submitformURL',{
lastname: this.lastname,
generatedcode: this.generatedcode,
})
}
created: function () {
axios.get('/generate_inputURL').then(this.OnSuccess);
}
HTML
<div v-html="generatedform"></div>
GENERATED INPUT
<input type="text" value="" v-model="generatedcode"/>

Try:
created: function () {
axios.get('/generate_inputURL').then(res => this.OnSuccess(res));
}

Component data must be function not object. You should be seeing warning about this in console. I guess your component is not reactive data then, which means that is not redrawn after on request done.
data(): {
return {
generatedform:'',
generatedcode:''
}
}

As I can see, you want to change the vue-app template using v-html attr - I think this is not possible. While mounting the application, the template compiles into render function, so your trick does not make any sense. You can try to do the following:
Construct the template (using html recieved from server as you want ) as string or as hidden el in the DOM
Set it in your app object - template:your_html_template
Create vue app

Related

Unable to add elements using the setAttribute

I am using the VUE JS code and trying to add the setAttribute to some of the tags.
Here is the code I am using :
changetab() {
const demoClasses = document.querySelectorAll(".delCon__select");
demoClasses.forEach(button => {
button.setAttribute("tabindex", "0");
});
return true;
},
but when I view in the code inspector, It does not show added to it, I have added the above function in computed.
template is like this :
<template>
<el-container class="orders"></el-download>
</template>
You need to make this type of request in Vue's Lifecycles, like: created or mounted.
Something like:
mounted() {
this.changetab()
}
Computed would not be the most appropriate place for this type of action.

How can I update the msg variable in the following code?

I have written the following code in a single Vue component. I am very new to Vue. I want to know how can I update the msg variable in the following and pass the updated value to the template in this Vue component:
<template>
<div class="dropzone">
<form id="dropzone" method='POST' enctype="multipart/form-data" v-on:drop="upload" #dragover.prevent>
<my-vue-component v-model="msg" ref="markdownEditor" />
</form>
</div>
</template>
<script>
export default {
data: () => {
return {
msg: 'zyx'
}
},
methods: {
upload: (e) => {
self.msg = '123'
}
}
}
</script>
I am really stuck and none of the links that google redirects me to are out of my reach. Because all of them either talk about new Vue({}) or dont provide much on export default.
Am I doing something wrong here?
I have also tried this.msg, but then I get the error saying msg of undefined...
Change this:
upload: (e) => {
self.msg = '123'
}
to this:
upload (e) {
this.msg = '123'
}
Note that upload (e) { is short-hand for upload: function (e) {.
The key changes are:
Use this instead of self.
Don't use an arrow function because that binds this to the surrounding scope and in this case that's the global scope. What you want is for this to be bound to your component instance (which is actually a Vue instance) so you need to use a normal function. Vue tries to ensure the binding is correct but it can't do that with an arrow function because it is already bound.
The config options that appear in a component like this are almost all the same as the config options that you would pass to new Vue, so if you see examples that are using the other one it will rarely make any difference. Usually it is pretty obvious when a config setting doesn't make sense for one or the other.

v-model not always updating in Vue

Short question
The v-model which binds a string to an input field won't update in some cases.
Example
I am using Vue within a Laravel application. This is the main component which contains two other components:
<template>
<div>
<select-component
:items="items"
#selectedItem="updateSelectedItems"
/>
<basket-component
:selectedItems="selectedItems"
#clickedConfirm="confirm"
#clickedStopAll="stopAll"
/>
<form ref="chosenItemsForm" method="post">
<!-- Slot for CSRF token-->
<slot name="csrf-token"></slot>
<input type="text" name="chosenItems" v-model="selectedItemsPipedList" />
</form>
</div>
</template>
<script>
export default {
props: ["items"],
data: function() {
return {
selectedItems: [],
selectedItemsPipedList: ""
};
},
methods: {
updateSelectedItems: function(data) {
this.selectedItems = data;
this.selectedItemsPipedList = this.selectedItems
.map(item => item.id)
.join("|");
},
confirm() {
this.$refs.chosenItemsForm.submit();
},
stopAll() {
this.updateSelectedItems([]);
this.confirm();
}
}
};
</script>
The method updateSelectedItems is called from the select-component and it works fine. In the end, the selectedItemsPipedList contains the selected items from the select-component, which looks like "1|2|3" and this value is bound to the input field in the chosenItemsForm. When the method confirm is called from the basket-component, this form is posted to the Laravel backend and the post request contains the chosen items as piped list. So far, so good.
The method stopAll is called from the basket-component and it will remove all the selected items from the array. Therefore it will call the method updateSelectedItems with an empty array, which will clear the selectedItems array and then clear the selectedItemsPipedList. After that, confirm is called which will post the form again. But, the post value still contains the selected items (e.g. '1|2|3'), instead of "". It looks like the v-model in my form is not updated, which is strange because it does work when selecting items. Why is it working when adding items, and doesn't when removing all items?
I believe you have a timing issue here. The value of the properties haven't been propagated to the DOM yet, so the form submission is incorrect. Try this instead:
stopAll() {
this.updateSelectedItems([]);
//NextTick waits until after the next round of UI updates to execute the callback.
this.$nextTick(function() {this.confirm()});
}

Can I get Vue.js component as an instance?

I try to get the template of Vue.js component since I need it for another function.
First,
I have a function that needs a Vue.js component template because I want the data in the template to dynamically change and not just some static HTML.
Secondly,
I have a problem to get a template from Vue.js component. Maybe they are not allowed to do that but I am not sure. I am new to Vue.js.
But from my understanding of JS, maybe this can happen.
I am tried to do something like this:
let vmComponent = Vue.component('VueComponent', {
data() {
return {
title: 'I am a Vue.js component manually.'
}
},
template: `
<div>
<h2>Template Exchange</h2>
<h3>{{ title }}</h3>
</div>`,
});
console.log(vmComponent.template);
I hope to get the HTML string when I run vmComponent.template
If this way of doing things is not possible. Is there any other ways I can get Vue.js component template as HTML String.
For example, maybe in a new.Vue({})
It's possible to access component template with vmComponent.options.template.
A template can be declared as a string for reuse:
export const template = `...`;
const vmComponent = Vue.component('VueComponent', {
template,
...
});
This may not work with pre-compiled templates.

Does Vue have bilateral bind?

<p contenteditable="true" v-bind="message"></p>
Object #message does not change when I edit the HTML element. Is there any simple way to do this using Vue.js?
Unfortunately, contenteditable doesn't work with Vue bindings such as v-model, it's recommended that you use a library such as medium.js to build your own component.
However, if you're just trying to do something simple and keep the data in sync you can probably do that yourself:
View Model
new Vue({
el: '#app',
methods: {
updateMessage() {
this.message = this.$refs.message.innerText;
}
},
watch: {
message() {
this.$refs.message.innerText = this.message;
}
},
data: {
message: 'Hello'
}
})
HTML
<p ref="message" contenteditable="true" #keyup="updateMessage" class="editable">{{message}}</p>
 
As you can see you have to deal with updating the DOM yourself when using contenteditable. What I'm actually doing here is using a ref to target the contenteditable, so I can get the inner text via this.$refs.message.innerText. I've then added a #keyup event which calls the updateMessage method to update the message data property. I've then added a watcher which reverses this process, so when message is updated it updates the contenteditable.
Here's the JSFiddle: https://jsfiddle.net/3ngc9486/
Yes it has a two-way binding directive v-model, but it works only with input elements. So, instead of using a p element and handling that with complex JS, use a textarea with v-model and it will work out of the box.
<textarea v-model="message"></textarea>
here is an example.