简体   繁体   中英

VueJs 2: How to display prop in another component?

I have a simple question, but cannot find how to solve.

There are 2 Vue 2 Components. In Component 1, two props are passed, which therefore are used in Component 2.

// Component 1
Vue.component('component1', {
    props: {
        titleTest: {
            type: String,
            required: true
        },
        textTest: {
            type: String,
            required: true
        }
    },
    template: `
    <div>
        <div :title="titleTest">{{ titleTest }}</div>
        <div :data-test="textTest">{{ textTest }}</div>
    </div>
    `,
    created() {
        console.log('Created1');
        this.$root.$refs.component1 = this;
    },
    methods: {
        foo: function() {
            alert('this is component1.foo');
        }
    }
});

// Component 2
Vue.component('component2', {
    template: `
    <div>
        <div>Some text</div>
        <ul>
            <li>List Item1</li>
            <li>List Item2</li>
        </ul>
        <div>
            <button id='test' type="submit" @click="bar">Text</button>
            <component1 ref="component1" :title="test1" :data-test="test2"></component1>
        </div>
    </div>
    `,
    data: function() {
        return {
            test1: 'testText1',
            test2: 'testText2'
        };
    },
    methods: {
        bar: function() {
            this.$root.$refs.component1.foo();
        }
    },
    created: function() {
        console.log('Created2');
    }
});

new Vue({
    el: '#plotlyExample',
});

My idea, when I use Component 1 in Component 2 HTML template and bind data variables, they should be displayed. However, Vue sets only "title" and "data-test" but {{ titleTest }}, {{ textTest }} are not displayed. Additionally Vue sets props in one div, instead of two separate.

截屏

My ideal result is:

在此处输入图像描述

You named your props titleTest and textTest , that means you need to pass title-test and text-test , NOT title and data-test .

The reason they end up in your main <div> is because when Vue doesn't recognise them as props (because you used different names), it falls back on assuming they're regular HTML attributes (like class , id , and style )

In order for it to work, you either need to rename your props to title and dataTest in Component1, or you should use the title-test and text-test names in Component2.

You just need pass props to the component1

<component1 ref="component1" :title-test="test1" :text-test="test2"></component1>

you are missnaming the props in the component1 ( child component ), you used title and data-test but your props names are titleTest and textTest ! so you should use title-test and text-test instead.

:prop-name="propValue"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM