【问题标题】:Vue template does not update value (composition api)Vue模板不更新值(组合api)
【发布时间】:2020-12-22 17:01:47
【问题描述】:

我有一个功能组件:

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.js vue-composition-api


    【解决方案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 的更多信息。

    【讨论】:

    • 啊,我很接近。我试过了,但试图直接在toggleValue 上设置更改后的切换值,这会给出错误,因为该属性是一个引用,我无法直接在其上设置布尔值。但必须将其设置在 toggleValue ref 属性的值成员上。
    • 模板中使用的可以更改的每个值都必须是 reference() 或 ref() 实例?
    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2017-11-23
    • 2019-07-29
    • 2021-01-10
    • 2014-08-15
    • 2021-11-01
    • 2021-11-21
    • 2020-09-24
    相关资源
    最近更新 更多