【问题标题】:When is computed property going to be triggered, VueJS什么时候触发计算属性,VueJS
【发布时间】:2019-03-02 00:31:05
【问题描述】:

假设我有一个包含<input> 和'' 的表单。我想实现computed property,它将监视<input>,并且每次用户从这个<input> 中删除所有内容时,computed property 应该将<select> 返回到它的默认状态。

代码如下:

<input class="form-control"/>
<select v-model="selectModel">
   <option>Please select</option>
   <option>Yes</option>
   <option>No</option>
</select>



<script>
 new Vue({
    el: '#app',
    data() {
       return {
          selectModel: '';
       }
    },
    computed: {
       input_empty: function() {
            var inp = getElementByClass('form-control');
            if (inp == '') {
                selectModel = "Please select";
            }
       }
    }
 })
 </script>

这个computed property什么时候会被触发?我在想每次我在输入字段中输入内容时,或者当我从中删除所有内容时都会触发它,所以我在计算函数的第一行放置了一个断点,但它永远不会被触发。

【问题讨论】:

  • 不要为此使用计算。顾名思义,computed 是可以从您的视图模型的值中计算出来的。
  • @connexo 实际上你是对的,我对此很陌生,现在我看到我应该使用 watch 而不是 computed

标签: vue.js


【解决方案1】:

您可以查看输入的值,只要它是一个空字符串,您还可以重置您的selectModelhttp://jsfiddle.net/eywraw8t/395052/

模板:

<div id="app">
  <input class="form-control" v-model="textInput" />
  <select v-model="selectModel">
     <option value="" disabled>Please select</option>
     <option value="Yes">Yes</option>
     <option value="No">No</option>
  </select>
</div>

Vue:

new Vue({
  el: '#app',
  data() {
    return {
        selectModel: '',
      textInput: 'input'
    }
  },
  watch: {
    textInput: function () {
      if(this.textInput.trim() === '') {
        this.selectModel = ''
      }
    }
  }
})

【讨论】:

    【解决方案2】:

    你也可以使用方法来做你需要的事情,并用@change包装你的输入,这样你就可以用你的代码调用一个方法

    html

    <div id="app">
      <div class="container">
        <input class="form-control" v-model="myinput" @change="checkInput">
    <select v-model="selectModel">
       <option value="Please select" seleceted>Please select</option>
       <option value="Yes">Yes</option>
       <option value="No">No</option>
    </select>
    
      </div>
    </div>
    

    vue 代码

    var app = new Vue({
      el: '#app',
      data: () =>  ({
        selectModel: '',
        myinput: ''
      }),
      methods: {
        checkInput() {
          if (this.myinput === '') {
            console.log('here')
            this.selectModel = 'Please select'
          }
        }
      }
    })
    

    【讨论】:

    • 谢谢你的回答,不过watch这个时候更适合我
    猜你喜欢
    • 2019-12-05
    • 2010-11-18
    • 2019-09-10
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多