首页 > 解决方案 > Vue模板不更新值(组合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。

标签: vue.jsvue-composition-api

解决方案


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

所以你应该做这样的事情:

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的更多信息。


推荐阅读