【问题标题】:Dynamically create a Vue model based on ID根据 ID 动态创建 Vue 模型
【发布时间】:2017-02-27 11:21:16
【问题描述】:

我有一个输入没有任何 Vue 指令:

<input type="text" id="name" />

现在我正在构建一个自定义 Vue 组件,它接受一个名为 input 的参数,该参数应该是该输入的 DOM 选择器:

<component input="#name"></component>

现在我想根据输入的值切换组件模板中的一个类,类似于表单输入绑定。但是,由于我们在组件内部,我猜无法使用模型绑定。所以我尝试创建一个计算属性:

<template>
    <div v-bind:class="[inputValue ? 'active' : '']"></div>
</template>

<script>
    module.exports = {
        props: [
            'input'
        ],
        computed: {
            inputValue: function () {
                return $(this.input).val();
            }
        }
    }
</script>

很遗憾,这不起作用。有人知道在此组件中查看“外部”输入值的解决方法吗?

(注意:为简洁起见,省略了组件的主要功能)

【问题讨论】:

    标签: model vue.js


    【解决方案1】:

    MVVM 旨在让您无需通过 id 直接访问 DOM 对象,而是将它们绑定到模型数据:

    <input type="text" v-model="name" />
    ...
    <script type="text/javascript">
    new Vue({
      data: {
         name: ""
       }
    });
    </script>
    

    然后您可以将数据作为道具传递给您的组件:

    <component :input="name"></component>
    

    现在你有了数据,你可以用它来代替:

    <template>
        <div v-bind:class="[isActive() ? 'active' : '']"></div>
    </template>
    
    ...
    methods: {
       isActive : function() {
         return this.input;
       }
    }
    ...
    

    编辑:

    我只想指出,我只是按照您的示例使用return this.input;,但除非您将值转换为布尔值,否则这实际上不起作用。最好确保你只从函数中返回 true 或 false:

       isActive : function() {
         return (this.input == "") ? false: true;
       }
    

    【讨论】:

    • 如果不明确定义表单输入绑定,真的没有办法获得类似模型的行为吗?
    • 从技术上讲,您尝试做的事情是可能的,您需要在您的 inputValue 计算中执行以下操作:$(this.$parent.$el).find(this.input).val(),但这并不是 vue 的真正用途。跨度>
    • 好的。所以现在我尝试了建议的代码。是否可以检索模型的 DOM 元素,以便在安装组件期间附加悬停侦听器?
    • 我不认为你可以从child 组件中附加任何东西到parent,但是如果你想在模板本身中获取元素那么它只是$(this.$el)
    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多