vue.js - 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。
解决方案
现在该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>
查看文档以获取有关ref和reactive的更多信息。
推荐阅读
- xaml - 如何在 uwp 应用程序中通过扫描仪扫描图像
- unity3d - 如何在光子网络中同步 GameObject 变量?
- sql - 从 SQL Server 获取 MicrosoftAccount 登录
- java - 在 stream().filter 中做大于或等于过滤器
- python - 大熊猫 CSV 中的 dropna() 导致 KeyError: MemoryError
- java - 下面附表如何更完善?
- css - 标题与其他正文元素重叠;
- rest - System.LimitException:BMCServiceDesk:SOQL 查询过多:101
- ajax - 使用带有 CORS 策略的 ajax 调用问题调用 IIS 发布的 Web api
- angular - 如何使用量角器打字稿在地图元素上单击选择拖动