【问题标题】:Vue - Change in the state does not re render the template?Vue - 状态变化不会重新渲染模板?
【发布时间】:2019-07-21 15:09:18
【问题描述】:

我正在尝试了解 Vue 的基础知识,到目前为止,我所了解的是,每当数据属性中的任何状态发生变化时,模板或组件都应该重新呈现。这是我正在使用的代码 sn-p。

index.html

<div id="app">
  <h3>Generator</h3>
  <div>
    Input: 
    <input @input="onInput"/>
  </div>

  <div>
    Output: 

    {{test()}}

  </div>
</div>

ma​​in.js

new Vue({
  el:'#app',
  data: {
    textInput: ''
  },
  methods: {
    onInput(event){
      this.textInput = event.target.value
    },
    test(){
      console.log("Test running")
    }
  }
})

我预期会发生什么?

由于我每次击键都会更新textInput 数据属性,我认为由于模板会重新呈现自身,因此每次我按下一个键时我都会在控制台中看到Test running 消息,因为页面每次都会重新渲染,我会看到输入字段为空白。

目前发生的情况

  1. 当我运行代码时,我看到test 函数只运行一次。
  2. 我没有看到每次击键时都有空白输入字段

【问题讨论】:

  • 现在没有重新渲染,因为它没有绑定到任何 DOM 元素。您能否详细说明您要达到的目标?你想在每次击键时重新渲染一个 dom 元素吗?

标签: vue.js vuejs2


【解决方案1】:

DOM 不依赖于textInput,因此对其进行更改不会导致重新渲染。如果渲染函数使用了变量,当变量改变时,你会得到重新渲染。

new Vue({
  el:'#app',
  data: {
    textInput: ''
  },
  methods: {
    onInput(event){
      this.textInput = event.target.value;
    },
    test(){
      console.log(this.textInput);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h3>Generator</h3>
  <div>
    Input: 
    <input @input="onInput"/>
  </div>

  <div>
    Output: 
    {{textInput.length}}
    {{test()}}

  </div>
</div>

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多