Vue模板不更新值(组合API)

时间:2020-09-03 12:42:29

标签: vue.js vue-composition-api

我有一个功能组件:

export default defineComponent({
  name: 'MovieOverview',
  components: {
    ExpandedMovieInformation,
  },
  setup() {
    let toggleValue = false;

    const toggleExpandedMovieInformation = (moviex: Movie) => {
      toggleValue = !toggleValue;
      console.log(toggleValue)
    };

    return {
      toggleValue,
      toggleExpandedMovieInformation,
    };
  },
});

<template>
  <div>
    <button v-on:click='toggleExpandedMovieInformation'>click</button>
    {{ toggleValue }}
  </div>
</template>

当我单击按钮时,console.log确实记录了更改,但是模板中的toggleValue保持相同的值:false。

1 个答案:

答案 0 :(得分:1)

现在toggleValue变量没有反应。您应该使用ref()reactive()来使其具有反应性,这样,每次对该属性进行更改时,视图都会重新呈现。

因此,您应该执行以下操作:

import { ref } from 'vue'

export default defineComponent({
  name: 'MovieOverview',
  components: {
    ExpandedMovieInformation,
  },
  setup() {
    let toggleValue = ref(false);

    const toggleExpandedMovieInformation = (moviex: Movie) => {
      // now you'll have to access its value through the `value` property
      toggleValue.value = !toggleValue.value; 
      console.log(toggleValue.value)
    };

    return {
      toggleValue,
      toggleExpandedMovieInformation,
    };
  },
});

<template>
  <div>
    <button v-on:click='toggleExpandedMovieInformation'>click</button>
    <!-- You DON'T need to change toggleValue to toggleValue.value in the template -->
    {{ toggleValue }}
  </div>
</template>

检查文档以获取有关refreactive的更多信息。