Juan Lago
Juan Lago

Reputation: 1048

Display value emitted from Vue component

I created two separated Vue components and I able to emit a message thru a bus.

How can I render/display the message in the component that receives the message.

Example of the Vue component that receives the message:

<template>
    <div v-model="cars">
        Car model: {{ model }}

        <input type="button" @click="display" value="example" />
    </div>

</template>


<script>
    export default {
        data() {
            return {
                cars: null
            }
        },
        mounted() {
            bus.$on('CARS_LOADED', (cars) => {
                this.cars = cars;
            });
        },
        methods: {
            display()
            {
                console.log(this.cars);
            }
        }
    }
</script>

I can successfully emit and received the message, however the car model is not updated. I checked the message received and it contains the "model" key with a right value.

I cannot see any error in the Vue console and however if I replace "{{ model }}" by "{{ cars }}" I can see the full message object updated.

I am using Vue 2.x.

Update: I enclose an example: https://jsfiddle.net/kvzvxk4f/1/

As you can see in the example I cannot render an specific field from the object, however I can render the object as string.

Upvotes: 0

Views: 19666

Answers (2)

Juan Lago
Juan Lago

Reputation: 1048

I found the answer.

I just have to type property separated by ".". Like for example {{cars.model}}.

<template id="compo2">
  <div>
    <div>
       {{ field.name }}
    </div>
    <div>
      Received: {{ field }}
    </div>
  </div>
</template>

Example: https://jsfiddle.net/zuhb7s8q/3/

Upvotes: 0

Hammerbot
Hammerbot

Reputation: 16364

I think that you are misunderstanding some parts of the vue syntax.

How to access properties of an object:

You just need to write {{ car.model }} to access a property of an object.

How to iterate through an array in a template:

If you want to display all the cars in your template, you should write:

<div v-for="car in cars">
    {{ car }}
</div>

As you see, the v-for directive allows you to iterate through an array.

What is v-model?

v-model is used to bind a variable to an input or a component.

<template>
    <div>
        <input type="text" v-model="foo" />
    </div>
</template>

<script>
export default {
    data () {
        return {
            foo: 'bar'
        }
    }
}
</script>

In that case, the foo property will be bound to the input text.

Last point:

In your case, to make it work, you also need to create a root element for your template, because a template can't have multiple root elements:

<template>
    <div>
        <div v-for="car in cars">
            {{ car }}
        </div>
    </div>
</div>

Upvotes: 4

Related Questions