更改另一个变量时,无法更改一个变量的值

时间:2020-11-11 20:36:54

标签: vue.js

当我输入'count'的值时,想要立即更改'countcolor'的值。 我不了解值的绑定,还是需要引入此组件? 该怎么办?

<div id="app-13"> 
            give a count to know the color (0,1 or anything)<br>
            <input type="text" name="" v-model="count" v-on:keyup.enter="cometh"><br> 
            <p>when the count is {{ count }}<br>
              color is <span>{{ countcolor }}</span>
            </p>
          </div>

而js是:

var app13 = new Vue({
  el: '#app-13',
  data: {
    count: 0,
    countcolor: 'green'
  },
  methods:{
        cometh: function(){
            
            if(this.count === 0){
                this.countcolor === 'green'
            }else if(this.count === 1){
                this.countcolor === 'red'
            }else{
                this.countcolor === 'blue'
            }
        }
    }
  
})

1 个答案:

答案 0 :(得分:1)

这可以使用以下计算属性来实现

var app13 = new Vue({
  el: '#app-13',
  data: {
    count: 0,
  },
  computed:{
        countcolor() {       
            if(this.count === 0){
                return 'green'
            }else if(this.count === 1){
                return 'red'
            }else{
                return 'blue'
            }
        }
    }
})

然后您可以通过

进行渲染
<div id="app-13"> 
            give a count to know the color (0,1 or anything)<br>
            <input type="text" name="" v-model="count"><br> 
            <p>when the count is {{ count }}<br>
              color is <span>{{ countcolor }}</span>
            </p>
          </div>