vue pass data to component code example
Example 1: props vue js
Vue.component('my-component', {
props: {
// Basic type check (`null` and `undefined` values will pass any type validation)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Number with a default value
propD: {
type: Number,
default: 100
},
// Object with a default value
propE: {
type: Object,
// Object or array defaults must be returned from
// a factory function
default: function () {
return { message: 'hello' }
}
},
// Custom validator function
propF: {
validator: function (value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
Example 2: how to access both child event param and parent param in vue
<template>
<ul>
<product v-for="product in products"
:product="product"
@add="addToChart" />
</ul>
</template>
<script>
const Product = {
props: ["product"],
render(h) {
return h("li", { on: { click: this.click } }, this.product);
},
methods: {
click() {
this.$emit("add", { product: this.product, quantity: 42 });
}
}
};
export default {
data() {
return {
products: ["Foo", "Bar"]
};
},
components: {
Product
},
methods: {
addToChart({ product, quantity }) {
console.log(product, quantity);
}
}
}
</script>
Example 3: pass method as props vue
//You should probably not pass methods as props in Vue, instead, emit an event.
//In parent component, do for example:
<Child-Component @alert="sayHi" />
methods: {
sayHi() {
alert('Hi')
}
}
// In child component, do:
<element @click="doSomething">
methods: {
doSomething() {
this.$emit('alert')
}
}
Example 4: vue passing props
<blog-post v-bind:title="post.title"></blog-post>
<blog-post
v-bind:title="post.title + ' by ' + post.author.name"
></blog-post>