我有一个功能组件:
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。
答案 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>