【问题标题】:VueJs 2: How to display prop in another component?VueJs 2:如何在另一个组件中显示道具?
【发布时间】:2021-08-15 09:44:19
【问题描述】:

我有一个简单的问题,但找不到解决方法。

有 2 个 Vue 2 组件。在组件 1 中,传递了两个 props,因此在组件 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',
});

我的想法,当我在组件 2 HTML 模板中使用组件 1 并绑定数据变量时,它们应该会显示出来。但是,Vue 只设置了“title”和“data-test”,但不显示 {{ titleTest }}、{{ textTest }}。此外,Vue 将 props 设置在一个 div 中,而不是两个单独的。

我的理想结果是:

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    您将道具命名为titleTesttextTest,这意味着您需要传递title-testtext-testNOT titledata-test

    它们最终出现在您的主要 &lt;div&gt; 中的原因是,当 Vue 不将它们识别为道具时(因为您使用了不同的名称),它会假设它们是常规的 HTML 属性(例如 classidstyle)

    为了使其工作,您需要在 Component1 中将您的 props 重命名为 titledataTest,或者您应该在 Component2 中使用 title-testtext-test 名称。

    【讨论】:

      【解决方案2】:

      您只需将道具传递给component1

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

      【讨论】:

        【解决方案3】:

        您在 component1(子组件)中命名错误,您使用了 titledata-test,但您的 props 名称是 titleTest 和 textTest!所以你应该改用title-testtext-test

        :prop-name="propValue"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-10-11
          • 2019-11-14
          • 2017-07-05
          • 2020-07-23
          • 2019-12-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多