【问题标题】:How to get component data? How to access the components from the outside?如何获取组件数据?如何从外部访问组件?
【发布时间】:2020-02-27 20:27:23
【问题描述】:

我导出组件:

<my-component> </my-component>

问题是如何获取这个特定组件的属性,只知道它的标签“my-component”?

更详细的问题描述: 使用 vue-cli-service build --target wc --name my-component my-component.vue 命令,编译成js文件

然后我将这个脚本连接到站点的标题中。

那我用组件

但是现在如何获取该组件的属性,一般如何访问该组件呢?如何获取该组件中的输入字段值?

对不起,我可能没有解释清楚。

我需要这样的东西:

<my-component id="my-component"> </my-component>
<script>
let inputValue = $("#my-component").find("input").val();//but this not work
</script>

或者

<script>
let props = <my-component></my-component>// this component props
</script>

在 my-component.vue 文件中,这段代码:

<template>
    <input :placeholder="test" type="text" name="test" value="">
</template>

<script>
    export default {
        name: 'MyInputComponent',
        props: {
            placeholder: {
                type: String,
                default: "00"
            }
        },
        data () {
            return {
            }
        },

    }
</script>

【问题讨论】:

标签: vue.js vue-component


【解决方案1】:

用法

    <template>
        <input :placeholder="placeholder" type="text" @input="emitInputValue">
    </template>

    <script>
        export default {
            name: 'MyInputComponent',
            props: {
                placeholder: {
                    type: String,
                    default: "00"
                }
            },
            methods: {
              emitInputValue ($event) {
              this.$emit('input', $event.target.value)
              }
           }

        }
    </script>

get value
<my-component @input"getValue"> </my-component>

methods: {
 getValue (payload) {
  console.log(payload)
 }
}

【讨论】:

  • 对不起,我可能没有解释清楚。我需要这样的东西: let inputValue = $("#my-component").find("input").val()
【解决方案2】:
<template>
    <input :placeholder="test" :id="id" type="text" name="test" value="">
</template>

<script>
    export default {
        name: 'MyInputComponent',
        props: {
            placeholder: {
                type: String,
                default: "00"
            },
            id: {
                type: String 
            }
        },
        data () {
            return {
            }
        },

    }
</script>

现在您的 id 将可用,您可以为所欲为。

我只想提出一个建议:当您使用 vue.js 时,请尝试避免使用 jquery 来获取输入值。 vue.js 本身有很多方法可以获取输入文本值。

如果您需要其他东西,请告诉我

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2017-04-11
    • 2019-08-01
    • 2019-11-05
    • 2019-05-01
    相关资源
    最近更新 更多