Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs : passing props down to a component in javascript?

Tags:

vue.js

How can i pass down props to a javascript Vue component.

this is how i normally do it.

<child prop="value"></value>

but i want to do it like this

var Child = Vue.extend({
    ...
});
Chid.passProps( {foo: 'bar'} ) // some thing like this?

is this possible in vue.js?

this is the full code:

var Child = Vue.extend({
    props: ['foo'],
    methods: {
        printIt: function() {
            console.log(this.foo)
        }
    },
    template: '#example'
});
var vm = new Vue({
    el: '#root',
    data: {
        foo: 'bar'
    },
    render: function(createElement) {
        return createElement(Child); // pass down foo
    }
});

link to jsbin

like image 302
bazi Avatar asked Dec 10 '16 08:12

bazi


People also ask

How do I pass a Vue prop in JavaScript?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.

Can you pass functions as props in Vue?

While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem. If you keep reading you'll see what I mean. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.


1 Answers

Please read the section on render functions https://v2.vuejs.org/v2/guide/render-function.html#createElement-Arguments

Essentially you need to pass the props with the call to the render function as part of the data element

var vm = new Vue({
    el: '#root',
    data: {
        foo: 'bar'
    },
    render: function(createElement) {
        return createElement(Child, {
            props: {
                foo: this.foo
            }  
        })
    }
});
like image 75
vbranden Avatar answered Oct 11 '22 08:10

vbranden