I want to post json data from Vue to php, but I'm struggling to find a way to pass input value data from Vue component to root element. When I call method submitProduct, alert message simply gives me 'undefined'. I had to strip my original code because of that stupid post balance policy. What's wrong here?
var productForm = Vue.createApp ({
methods:{
submitProduct: function(){
alert(JSON.stringify(productForm.product))
this.postData(productForm.product)
},
postData: function(p){
fetch('mysql_postdata.php', {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({p:p})
//body: 'd='+d
})
}
}
})
productForm.component('custom-form', {
props: ["value"],
template: `
<label>SKU<input type="text" :value=this.product.sku></label>
<label>Name<input type="text" :value=this.product.name></label>
<label>Price<input type="text" :value=this.product.price></label>
` ,
data: function() {
return {
product: {
sku: 0,
name: 'asdf',
price: 0
},
options: ['Size', 'Weight', 'Dimensions'],
selected: 'Size'
}
}
})
productForm.component('status-bar', {
props: ['info'],
template: '<p>{{ selected }}</p>'
})
const vm = productForm.mount('#product_form')
The product state belongs to the custom-form component so the root app cannot access the state.
If you trying to create a form and get the input from the form, you need to do 1 of this:
custom-form and bind an event to listen to the state change docs here. (only do this if the custom-form component is not deep down in the component tree)First of all after 3.5 days of struggling to try to understand Vue I came with tested successfull result. I want to thank you and anybody else, who helped me to understand basics principles in Vue! :) Please see link below...
https://jsfiddle.net/e2mnh4xa/
P.S. And yes! You are right about rearranging 'custom-form' tag. :)
html code:
<div id="product_form" v-cloak>
<custom-form>
</custom-form>
</div>
js code:
var productForm = Vue.createApp ({})
productForm.component('custom-form', {
props: {
modelValue: {
type: String,
default: ''
},
},
components: ['status-bar'],
template: `
<button v-on:click="submitProduct">Save</button>
<label>SKU<input type="text" v-model="this.product.sku"></label>
<label>Name<input type="text" v-model="this.product.name"></label>
<label>Price<input type="text" v-model="this.product.price"></label>
` ,
data: function() {
return {
product: {
sku: 0,
name: 'asdf',
price: 0,
},
options: ['Size', 'Weight', 'Dimensions'],
selected: 'Size',
outputData: ''
}
},
computed:{
model:{
get(){ return this.modelValue },
set(v){ this.$emit('update:modelValue',v)}
}
},
methods:{
submitProduct: function(){
alert (this.showData());
return this.postData(this.product)
},
showData: function(){
console.log(this.product.sku)
return JSON.stringify(this.product)
}
}
})
const vm = productForm.mount('#product_form')