Vue JS:设置计算属性不调用v-if

时间:2018-07-16 22:14:51

标签: vue.js

当方法设置计算属性时,不会调用v-if。我认为计算属性在逻辑上就像“常规”属性一样工作。

// theState can't be moved into Vue object, just using for this example
var theState = false; 
var app = new Vue({
  el: '#demo',
  data: {
  },
  methods: {
     show: function() {
        this.foo = true;
     },
     hide: function() {
        this.foo = false;
     }
  },
  computed: {
    foo: { 
      get: function() {
        return theState;
      },
      set: function(x) {
        theState = x;
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="demo">
  <input type=button value="Show" @click="show()">
  <input type=button value="Hide" @click="hide()">
  <div v-if="foo">Hello</div>
</div>

我做错什么了吗?

2 个答案:

答案 0 :(得分:1)

您需要将State移入数据。否则,它将不会是反应性的,因此vue不会知道它何时更改,因此v-if或任何其他反应性将无法工作。

var app = new Vue({
  el: '#demo',
  data: {
    foo2: false,
    theState: false
 // 1
  },
  methods: {
     show: function() {
        this.foo = true;
     },
     hide: function() {
        this.foo = false;
     }
  },
  computed: {
    foo: {            // 2
      get: function() {
        return this.theState
      },
      set: function(x) {
        this.theState = x;
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="demo">
  <input type=button value="Show" @click="show()">
  <input type=button value="Hide" @click="hide()">
  <div v-if="foo">Hello</div>
</div>

答案 1 :(得分:1)

Vue没有观察到组件外部变量的变化;您需要将该值导入组件本身,以使反应性发挥作用。

var theState = false;  // <-- external variable Vue doesn't know about
var app = new Vue({
  el: '#demo',
  data: {
     myState: theState // <-- now Vue knows to watch myState for changes
  },
  methods: {
     show: function() {
       this.foo = true;
       theState = true; // <-- this won't affect the component, but will keep your external variable in synch
     },
     hide: function() {
        this.foo = false;
        theState = false; // <-- this won't affect the component, but will keep your external variable in synch
     }
  },
  computed: {
    foo: { 
      get: function() {
        return this.myState;
      },
      set: function(x) {
        this.myState = x;
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="demo">
  <input type=button value="Show" @click="show()">
  <input type=button value="Hide" @click="hide()">
  <div v-if="foo">Hello</div>
</div>

(编辑以删除不正确的信息;我忘记了在那里存在一段时间的计算属性设置器)