Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vue.js - Pass Props component to root Instance

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...