问题描述
我正在制作一个简单的组件(SFC),该组件循环显示字符串列表,并将标题中的文本替换为该值。
由于我更喜欢结构和设计,我正计划对所有组件使用composition API。
我以为我已经正确制作了组件,但是它不会在DOM中自动更新。
日志正确显示了更新的值,但是在最初调用setup()之后,该值永不变。
Composition API样式(不更新DOM):
<template>
<div>
<h1>{{ text }}</h1>
</div>
</template>
<script>
import { ref } from "@vue/composition-api";
export default {
props: {
textList: Array,interval: Number
},setup(props) {
let text = ref(props.textList[0]);
let cycler;
function startCycling() {
let index = 0;
text = props.textList[index];
cycler = setInterval(() => {
if (index >= props.textList.length) {
index = 0;
}
console.log("Index: " + index);
text = props.textList[index];
console.log("Text: " + text);
index++;
},props.interval);
}
function stopCycling() {
clearInterval(cycler);
}
startCycling();
return { text,startCycling,stopCycling };
}
};
</script>
我想知道我是否在代码逻辑方面犯了一个错误,因此我使用Options API创建了相同的组件,并且该组件立即起作用:
Options API样式(适用):
export default {
props: {
textList: Array,data() {
return {
text: "",};
},methods: {
startCycling: function() {
let index = 0;
this.text = this.$props.textList[index];
cycler = setInterval(() => {
if (index >= this.$props.textList.length) {
index = 0;
}
console.log("Index: " + index);
this.text = this.$props.textList[index];
console.log("Text: " + this.text);
index++;
},this.$props.interval);
},stopCyling: function() {
clearInterval(cycler);
},},mounted() {
this.startCycling();
},}
如何在Vue的新Composition API中复制此功能?
我需要对text
做些什么,以允许我更改代码并保持反应性?
仅仅使用ref(text)
并返回它,似乎并没有这样做。
解决方法
调用startCycling();
钩中的onMounted
onMounted(() => {
startCycling();
})
但是您必须像使用ref
那样导入该钩子:
import { ref,onMounted } from "@vue/composition-api";
当您要更新使用ref创建的变量时,应将其值更改为
text.value = props.textList[index];
完整代码:
<script>
import { ref,onMounted } from "@vue/composition-api";
export default {
props: {
textList: Array,interval: Number
},setup(props) {
const text = ref(props.textList[0]);
let cycler;
function startCycling() {
let index = 0;
text.value = props.textList[index];
cycler = setInterval(() => {
if (index >= props.textList.length) {
index = 0;
}
console.log("Index: " + index);
text.value = props.textList[index];
console.log("Text: " + text);
index++;
},props.interval);
}
function stopCycling() {
clearInterval(cycler);
}
onMounted(() => {
startCycling();
})
return { text,startCycling,stopCycling };
}
};
</script