首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue.js 2:计算出的数据更改时不更新

Vue.js 2:计算出的数据更改时不更新
EN

Stack Overflow用户
提问于 2019-02-02 20:35:18
回答 1查看 117关注 0票数 1

HTML:

代码语言:javascript
运行
复制
<div id="app">
  <h3>My identicon generator</h3>
  <div>
    input:
    <input v-on:input="onInput"/>
  </div>

  <div>
    output:

    <div v-html="identicon"></div>
  </div>
</div>

JS:

代码语言:javascript
运行
复制
new Vue({
  el: '#app',
  data: {
    textInput: '',
  },
  computed: {
    identicon: function() {
      console.log('new identicon for:', this.textInput);
      return jdenticon.toSvg(this.textInput, 200);
    }
  },
  methods: {
    onInput: (e) => {
      this.textInput = e.target.value;
      console.log('is it set?', this.textInput);
    }
  }
});

Codepen:https://codepen.io/anon/pen/JxNrNP

我希望在输入字段中输入文本时,标识会得到更新。console.log(is it set?', this.textInput)运行正常,控制台中会显示textInput的最新值。但是,console.log('new identicon for:', this.textInput)仅在加载页面时运行,并且不会再次运行,这导致标识保持原样。为什么textInput更改时不调用computed方法?我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-02 20:46:21

我做了一些修改,现在它起作用了。1.-将数据对象更改为返回对象的函数2.-将@input更改为v-model

代码语言:javascript
运行
复制
new Vue({
  el: '#app',
  data(){
    return {
      textInput: '',
    }
  },
  computed: {
    identicon() {
      console.log('new identicon for:', this.textInput);
      return jdenticon.toSvg(this.textInput, 200);
    }
  },
  methods: {
    onInput: (e) => {
      this.textInput = e.target.value;
      console.log('is it set?', this.textInput);
    }
  }
});

按照预期工作。

https://codepen.io/anon/pen/ZwKazg?editors=1111

然而,我也修复了你的组织,这也行得通,你的问题与你的onInput方法和恒等计算属性的作用域有关。

这行得通,我把它们都改成了ES6函数。

代码语言:javascript
运行
复制
new Vue({
  el: '#app',
  data: {
    textInput: '',
  },
  computed: {
    identicon() {
      console.log('new identicon for:', this.textInput);
      return jdenticon.toSvg(this.textInput, 200);
    }
  },
  methods: {
    onInput(e) {
      this.textInput = e.target.value;
      console.log('is it set?', this.textInput);
    }
  }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54493131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档