Vue模板不更新值(组合api)
Vue template does not update value (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。
现在 toggleValue
变量没有反应性。您应该使用 ref()
或 reactive()
以使其具有反应性,以便每次对 属性.
进行更改时视图 re-renders
所以你应该这样做:
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>
我有一个功能组件:
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()
或 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>