【问题标题】:Vue2 error 'classList' of null errorVue2错误'classList'的空错误
【发布时间】:2017-08-22 20:33:15
【问题描述】:

所以我在 Vue 中扭动一个组件。只是一个简单的导航。使用方法我制作了一个活动脚本。我还制作了一个“创建的”加载函数脚本并控制台它的元素。

它在控制台中给我以下错误:

TypeError: Cannot read property 'classList' of null
at VueComponent.created (eval at <anonymous> (app.js:1002), <anonymous>:23:67)
at callHook (eval at <anonymous> (app.js:672), <anonymous>:2275:21)
at VueComponent.Vue._init (eval at <anonymous> (app.js:672), <anonymous>:3758:5)
at new VueComponent (eval at <anonymous> (app.js:672), <anonymous>:3922:12)
at createComponentInstanceForVnode (eval at <anonymous> (app.js:672), <anonymous>:3117:10)
at init (eval at <anonymous> (app.js:672), <anonymous>:2925:45)
at createComponent (eval at <anonymous> (app.js:672), <anonymous>:4656:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4599:9)
at createChildren (eval at <anonymous> (app.js:672), <anonymous>:4724:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4632:9)

奇怪的是,当我删除 .classList 时,它仍然给出 null 值而不是空数组。

这是我的组件代码(注意这是荷兰语):

<script>
export default {
    name: 'frontnav',
    data () {
        return {
            aantal: [
                'Aankomende Gasten',
                'In Huis',
                'Vertrekkende Gasten',
                'Dag Gasten'],
            dag: [
                'Vandaag',
                'Morgen',
                'Overmorgen',
                'Deze Week',
                'Volgende Week'],
            active: 'Aankomende Gasten'
        }
    },
    methods: {
        makeActive: function (aantal) {
            this.active = aantal;
            let el = document.querySelector('nav tr a:first-child');
            document.querySelector('.' + item).classList.add('active');
        },
        loadfunction: function () {
           const el = document.querySelector('nav a:first-child');
           el.classList.add('active');
        }
    },
    created () {
       this.loadfunction();
        console.log(document.querySelector('nav tr a:first-child').classList);
    }
}

【问题讨论】:

  • 在 Vue 中有更简单的方法来做你想做的事。通常,不需要使用 DOM 操作。如果你想展示你的模板,我可以提供一个例子。
  • 简单地用查询选择器解决了这个问题,但是 thxx @bert :)

标签: javascript syntax-error components vue.js


【解决方案1】:

created() 更改为mounted()

如果你正在操作 DOM,你最好等待它。

【讨论】:

  • 我为什么要等它?
  • 只是因为这是有道理的。
  • @Daniel 答案是因为您要操作的 DOM 在挂载之前不存在。
【解决方案2】:

刚刚发现const el = document.querySelector('nav a:first-child');

All 使其成为一个集合。 :/

应该是

const el = document.querySelectorAll('nav a:first-child');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-11-07
    • 2018-02-11
    • 1970-01-01
    • 2021-01-15
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多