javascript - Vue v-if 使用间隔时不影响 Dom
问题描述
我正在尝试setInterval
使用 Vue 进行轮询并有条件地渲染一些元素。但它不起作用,所以我将我的数据设置为true
但在 DOM 上什么也没发生。
PS:我使用 Vue.js 和 CDN,所以我的应用程序不是用 VueCLI 创建的。
这是我的 HTML:
<div id="app">
<div class="container">
<h1 v-if="showtext">
text
</h1>
</div>
</div>
这是我的脚本。当以状态 200 响应时,我的数据将切换为 true。我可以在控制台上看到它,但我的文本没有在 DOM 上呈现。
var app = new Vue({
el: "#app",
data: {
polling: null,
showtext: false
},
methods: {
pollData() {
this.polling = setInterval(() => {
axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/comments"
}).then(function(response) {
console.log(response);
if (response.status == 200) {
this.showtext = true
}
console.log(this.showtext)
});
}, 7000);
}
},
beforeDestroy() {
clearInterval(this.polling);
},
created() {
this.pollData();
},
});
解决方案
您应该使用箭头函数来访问 vue 实例范围:
then((response)=> { ...
this
或按如下方式分配给全局变量(这适用于旧浏览器):
var that=this; ///<------
axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/comments"
}).then(function(response) {
console.log(response);
if (response.status == 200) {
that.showtext = true
}
console.log(that.showtext)
});
完整运行示例:
Vue.config.devtools = false;
Vue.config.productionTip = false;
var app = new Vue({
el: "#app",
data() {
return{
polling: null,
showtext:false
}
},
methods: {
pollData() {
this.polling = setInterval(() => {
axios({
method: "get",
url: "https://jsonplaceholder.typicode.com/comments"
}).then((response)=> {
if (response.status == 200) {
this.showtext = true
}
console.log(this.showtext)
});
}, 4000);
}
},
beforeDestroy() {
clearInterval(this.polling);
},
created() {
this.pollData();
},
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
<div id="app">
<div class="container">
test:
<h1 v-if="showtext">
text
</h1>
</div>
</div>
推荐阅读
- python - 将带有多个 json 对象的推文 json 文件加载到 pandas 数据框中
- reactjs - 为什么在表单中单击输入类型 = 提交时会自动更改回我设置的状态?
- javascript - 我需要编写一个函数,该函数在华氏温度中采用单个参数并将其转换为摄氏度
- python - xlwings - This workbook contains links to other data sources - display_alert doesn't work
- c - 如何将命令行从 shell 脚本传递给 C 程序的命令行参数?
- python - 如何在 instapy 中配置代理
- excel - Google 表格公式需要根据 A 列中 3 个值中的 1 个和 B 列中 2 个值中的 1 个返回值
- process - At what interval does the processor compare processes and their burst times in SRTF algorithm?
- javascript - Angular + FileList 使用 FileReader 处理错误
- python - 如何使kivy布局和按钮周围的边框线可见