[英]Vue.js 3.0 - Update component UI when store property value changes via composition API
I am writing a Vue.js app using Vue.js 3.0.我正在使用 Vue.js 3.0 编写一个 Vue.js 应用程序。 I'm using this as a way to learn the composition API.
我用它作为学习组合 API 的一种方式。 One thing that is unclear to me is how to conditionally update my component UI when a store value is updated.
我不清楚的一件事是如何在更新商店值时有条件地更新我的组件 UI。 To demonstrate my issue, I've created this fiddle .
为了演示我的问题,我创建了这个 fiddle 。 The code is detailed here:
代码在这里详细说明:
JavaScript JavaScript
const store = {
state: reactive({
result = null
}),
generateNewValue() {
this.state.result = Math.floor(Math.random() * 10);
}
};
const MyApp = {
setup() {
return {
}
}
}
const myApp = Vue.createApp(MyApp)
myApp.component("banner",
{
template: '<button @click="onGenerateClick">generate</button>',
setup(props) {
console.log('setting up...');
},
methods: {
onGenerateClick() {
store.generateNewValue();
}
}
}
);
myApp.component("content", {
template: '<div><span>Content</span><button @click="onGenerateClick">generate</button></div>',
methods: {
onGenerateClick() {
store.generateNewValue();
}
}
});
myApp.mount('#my-vue')
HTML HTML
<div id="my-vue">
<banner></banner>
<hr />
<content></content>
</div>
CSS CSS
.even-banner {
background-color:navy;
color: #fff;
}
.even-content {
background-color:blue;
color: #fff;
}
.odd-banner {
background-color:maroon;
color:#fff;
}
.odd-content {
background-color:red;
color:#fff;
}
When I click the "generate" button, a random number is generated.当我单击“生成”按钮时,会生成一个随机数。 If that number is even, I want to set the
content
div to use the even
CSS class.如果该数字是偶数,我想将
content
div 设置为使用even
CSS 类。 If it is an odd number, I want to apply the odd
CSS class.如果是奇数,我想应用
odd
CSS 类。 I'm somewhat stuck though.我有点卡住了。
My problem is, I can successfully set the state value in the global store.我的问题是,我可以在全局存储中成功设置状态值。 However, I do not know how to react to property value changes in the components.
但是,我不知道如何对组件中的属性值更改做出反应。 I added a
watchEffect
, in my setup
functions.我在我的
setup
函数中添加了一个watchEffect
。 However, that does not give me access to the state of the individual component itself.但是,这并不能让我访问单个组件本身的状态。 I'm trying to figure out a way in each component to say "hey, when this property in the store changes, update the UI like this.".
我试图在每个组件中找出一种方法来说“嘿,当商店中的这个属性发生变化时,像这样更新 UI。”。
What am I missing?我错过了什么?
You could use a computed()
prop to track the state's value (eg, to test whether it's even):您可以使用
computed()
道具来跟踪状态的值(例如,测试它是否是偶数):
const MyApp = {
setup() {
return {
isEven: computed(() => store.state.result % 2 === 0)
}
}
}
Then, use that prop in the template to apply a conditional class :然后,在模板中使用该道具来应用条件类:
<content :class="{ 'even-content': isEven, 'odd-content': !isEven }">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.