Vue.js动态更改模板中的占位符

时间:2018-02-13 17:08:56

标签: templates dynamic vue.js vuejs2

我想在文本框的输入上动态更改模板中的占位符,但在更改值后它不起作用。最初它完美无缺。

演示

https://jsfiddle.net/he4gx40g/

工作示例谢谢@Roy J

https://jsfiddle.net/jadkLtc3/

组件示例(没有文本框逻辑)

<customValueComponent :item="config" :value="'ConfigValue1'" />

customValue组件的代码

customValueComponent: {
    props: {
        item: {
            type: Object,
            required: true
        },
        value: {
            type: String,
            required: true
        }
    },
    watch: {
        value: function (newVal, oldVal) { // watch it
            console.log('Prop changed: ', newVal, ' | was: ', oldVal)
            this.$options.template = '<div>{{ item.' + this.value + '}}</div>';
        }
    },
    created: function () {
        this.$options.template = '<div>{{ item.' + this.value + '}}</div>';
    },
    template: ''
}

对象

var config =
{
    ConfigValue1: "Titanium",
    ConfigValue2: "Gold",
    ConfigValue3: "Silver",
    ConfigValue4: "Bronze",
    ConfigValue5: "Copper",
    ...
};

1 个答案:

答案 0 :(得分:1)

$options is read-only。这不是您更改模板中的值的方式。 Vue在更改时更新值。您的组件定义应为

Vue.component('customvalue-component', {
    props: {
    item: {
      type: Object,
      required: true
    },
    value: {
      type: String,
      required: true,
    }
  },
  template: '<div>{{value}}</div>'
});

你对组件的绑定应该是

<customvalue-component :item="config" :value="config[value1]" />