html 当尝试显示Vue视图时,出现错误“无法读取null的属性(阅读“样式”)”

xzlaal3s  于 2023-06-20  发布在  其他
关注(0)|答案(2)|浏览(169)

我有一个标题与@click在我的身体。点击后,应该会显示一个Vue视图,但我得到的是错误:
Cannot read properties of null (reading 'style')
what I've read发生错误,因为document.getElementById("view")返回null,这可能有几个原因:
1.脚本在加载文档之前运行,因此找不到view项。
1.没有view项。
因为肯定有一个view项目,我猜第一个原因是导致错误,但我不明白为什么也不知道如何修复它。
下面是我的App.vue文件中的代码:

  1. <template>
  2. <h1 @click="showInfo()">Header</h1>
  3. <div class="view" style="display: none">
  4. <AnotherView />
  5. </div>
  6. </template>
  7. <style scoped>
  8. .view {
  9. }
  10. </style>
  11. <script>
  12. import AnotherView from "./views/AnotherView.vue";
  13. export default {
  14. components: { AnotherView },
  15. methods: {
  16. showInfo() {
  17. document.getElementById("view").style.display = "block";
  18. },
  19. },
  20. };
  21. </script>
nnvyjq4y

nnvyjq4y1#

您正在查询getElementById()中的一个类,正确的做法是通过用户@Sfili_81提到的ID来获取它。
而且你也应该使用$ref来做这个处理。

  1. <template>
  2. <h1 @click="showInfo()">Header</h1>
  3. <div ref="view-ref" class="view" style="display: none">
  4. <AnotherView />
  5. </div>
  6. </template>
  7. <style scoped>
  8. .view {
  9. }
  10. </style>
  11. <script>
  12. import AnotherView from "./views/AnotherView.vue";
  13. export default {
  14. components: { AnotherView },
  15. methods: {
  16. showInfo() {
  17. this.$refs.style.display = "block";
  18. },
  19. },
  20. };
  21. </script>
展开查看全部
t30tvxxf

t30tvxxf2#

你可以使用条件类像下面的源使用isShowInfo布尔标志(如果你想,切换)和编辑样式源块类是开/关

  1. <template>
  2. <h1 @click="showInfo()">Header</h1>
  3. <div class="view" :class="{ 'block': isShowInfo }">
  4. <AnotherView />
  5. </div>
  6. </template>
  7. <style scoped>
  8. .view {
  9. display: none;
  10. &.block {
  11. display: block;
  12. }
  13. }
  14. </style>
  15. <script>
  16. import AnotherView from "./views/AnotherView.vue";
  17. export default {
  18. components: { AnotherView },
  19. data () {
  20. isShowInfo: false,
  21. },
  22. methods: {
  23. showInfo() {
  24. this.isShowInfo = true
  25. },
  26. },
  27. };
  28. </script>
展开查看全部

相关问题