【问题标题】:Vue JS update computed property by user inputVue JS 通过用户输入更新计算属性
【发布时间】:2016-12-30 09:08:17
【问题描述】:

我的问题是用用户的输入替换计算属性的值。我的设置是这样的:

html

  <div class="col-md-3">
    <ul style="margin-top: 50px">
        <ol v-for="note in notes">
            <h3 @click="setActive($index)">{{note.name}}</h3>
        </ol>
    </ul>
</div>

<div class="col-md-9" v-show="activeNote">
    <h2 v-show="nameIsText" @click="switchNameTag()">{{activeNote.name}}</h2>
    <input class="form-control" v-show="!nameIsText" @keyup.enter="switchNameTag()" value="{{activeNote.name}}">

    <textarea name="note-text" class="form-control" rows=10>{{activeNote.text}}</textarea>
</div>

js

<script>
    var vm = new Vue({
        el: 'body',
        data: {
            active: {},
            nameIsText: true,
            notes: [{
                id: 1,
                name: 'Note 1',
                text: 'Text of note 1'
            }, {
                id: 2,
                name: 'Note 2',
                text: 'Text of note 2'
            }, {
                id: 3,
                name: 'Note 3',
                text: 'Text of note 3'
            }, {
                id: 4,
                name: 'Note 4',
                text: 'Text of note 4'
            }, {
                id: 5,
                name: 'Note 5',
                text: 'Text of note 5'
            }]
        },
        methods: {
            setActive: function(index) {
                this.active = index;
            },
            switchNameTag: function() {
                this.nameIsText = !this.nameIsText;
            },
        },
        computed: {
            activeNote: function() {
                return this.notes[this.active];
            },
        },
    });
</script>

我制作了一个简单的笔记应用程序,如果您单击一个笔记,则会显示一个带有文本的文本区域和一个带有名称的标题 2。 现在,如果您单击&lt;h2&gt;&lt;/h2&gt;-Tags 中的名称,标题 2 将替换为输入字段 - 因此用户可以编辑当前注释的名称。

一切正常,除了当我在输入字段中编辑名称(名称是计算属性)时,名称没有更新。第二个问题是,如果我在编辑一个笔记的名称后单击另一个笔记,旧笔记的名称仍保留在输入字段中,而不是显示新单击的笔记的名称。

我添加了两张图片以便更好地理解:

命名为 h2 名称作为输入

所以我的(可能相关的)问题是,如何在输入字段中编辑计算属性,并显示新单击的注释的名称,即使我在输入字段中编辑名称后没有按 Enter 键?

【问题讨论】:

    标签: javascript vue.js computed-properties


    【解决方案1】:

    您想为正在编辑的项目使用v-model 绑定。这些为您提供了将主动更新基础数据项的双向绑定。

    还需要使用v-if 而不是v-show,因为activeNote 可以是未定义的,在这种情况下访问其成员是错误的。

    <div class="col-md-9" v-if="activeNote">
      <h2 v-show="nameIsText" @click="switchNameTag()">{{activeNote.name}}</h2>
      <input class="form-control" v-show="!nameIsText" @keyup.enter="switchNameTag()" v-model="activeNote.name">
    
      <textarea name="note-text" class="form-control" rows=10 v-model="activeNote.text"></textarea>
    </div>
    

    Fiddle

    【讨论】:

    • 感谢您的帮助!这消除了我在 console.log 中的错误 :) 但仍然没有更新左侧导航中的名称和 h2-tag 中的名称。只保存输入字段的值..
    • @tossel 你拉小提琴了吗?它做你想做的事吗?
    • 哦,是的,谢谢,就像一个魅力..我有一个错字
    猜你喜欢
    • 2019-05-05
    • 2019-10-25
    • 2018-05-22
    • 2019-10-03
    • 1970-01-01
    • 2017-06-30
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多