I'm super newbie in vuejs. I don't know how to pass props component to root instance Here is my code.
component (Tesvue.vue)
<template>
<label class="col-md-2 control-label">{{name}}</label>
</template>
<script>
export default {
props: ['name']
}
</script>
Root (app.js)
window.Vue = require('vue');
import tesvue from './components/Tesvue.vue';
var vm = new Vue({
el: '#app',
components: {
tesvue
},
data:{
getname: ''
}
});
blade file
<div class="" id="app">
<tesvue name="{{$model->name}}"></tesvue>
</div>
The scenario is, im fetching data from laravel controller to blade element, then vue js can access it. This is like pass php variable to vuejs. I know this can be done with Php-vars-to-javascript plugin, or i can simply use it inline. like this var name = {{name}}
but i want do that in vuejs way (props).
So how to pass props data to root instance. How 'getname' can get props 'name' Thanks, sorry my bad english.
A component can not directly pass data back to its parent. This is only possible via events. So for this to work you'd have to emit an event from the child component as soon as its ready and have to listen for that event. In your case its like this:
Component (Tesvue.vue)
<template>
<label class="col-md-2 control-label">{{name}}</label>
</template>
<script>
export default {
props: ['name'],
mounted() {
this.$emit('setname', this.name);
}
}
</script>
Root (app.js)
window.Vue = require('vue');
import tesvue from './components/Tesvue.vue';
var vm = new Vue({
el: '#app',
components: {
tesvue
},
data: {
getname: ''
}
methods: {
changeName(name) {
this.getname = name;
}
}
});
blade file
<div class="" id="app">
<tesvue name="{{$model->name}}" @setname="changeName"></tesvue>
<!-- getname got set through changeName event -->
<span v-text="getname"></span>
</div>
Here's nice solution using dataset:
HTML:
<div id="app" data-name="dataname">
Component (Testvue.vue):
<template>
<label class="col-md-2 control-label">{{name}}</label>
</template>
Root Instance (App.js)
const root_element = document.getElementById('app');
new Vue({
el: root_element,
propsData: { name: root_element.dataset.name }
});
See more about propsData in the docs.
If you want to use multiple dataset at once, you can assign an object using spread operator like this: (if you're using Babel and have the object-rest-spread plugin)
const root_element = document.getElementById('app');
new Vue({
el: root_element,
propsData: { ...root_element.dataset }
});
Or, simply use ES6 method if you have not used Babel: (Object.assign())
propsData: Object.assign({},root_element.dataset)
So, if you have defined multiple dataset in your html like this:
<div id="app"
data-name="dataname"
data-another="anotherdata"
data-anything-else="anydata">
You can expose props like this:
export default {
// ...
props: ['name', 'another', 'anythingElse'],
// ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With