vue.js - 在vue中添加watch,在watch属性中添加会报错,通过实例的$watch方法添加是可以的,原因是什么?

查看:139
本文介绍了vue.js - 在vue中添加watch,在watch属性中添加会报错,通过实例的$watch方法添加是可以的,原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在vue中添加watch,在watch属性中添加,通过实例的$watch方法添加是可以的,原因是什么?但是我在html文件引入Vue,并在script中写,没有出现此问题。Vue文档中说,Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。这块不理解为什么出错。
下面是代码:

<template>
    <table id="datatable" class="table table-striped table-bordered">
        <thead>
            <tr>
                <th v-for="col in cols">
                    {{col}}
                </th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="item in items">
                <td v-for="col in cols">
                    {{item[col]}}
                </td>
            </tr>
        </tbody>
    </table>
</template>
<script>
import $ from 'jquery';
import dt from 'datatable';

export default {
    name: 'DataTable',
    props: {
        modulePath: {
            type: String,
            required: true
        },
        module:{
            type: Array,
            required: true
        }
    },
    data: function(){
        return {
            columns:[],
            items:[{username:'ddd',password:'123',email:'aaa',department:'kf',gender:'aa',name:'ddd',salt:'sss'}]
        }
    },
    computed: {
        cols: function(){
            this.columns = this.module;
            return this.module;
        }
    },
    created(){
        // 获取数据
    },
    mounted(){
        // 初始化Datatable
        var self = this;
        var unwatch = this.$watch('cols', function (newVal, oldVal) {
            $(this.$el).DataTable();
            unwatch();
        }, {deep: true});
    },
    watch: {
        cols: {
            deep: true,
            handle: function(){
                $(this.$el).DataTable();
            }
        }
    }
}
</script>

watch计算属性时有上面的问题,代码中cols属性会出现,非计算属性不会出现,items属性不会,但是columns属性在cols计算方法中赋值,也会出错

错误:

这个问题已被关闭,原因:问题已解决 - 问题已解决,且对他人无借鉴意义

解决方案

根据提示应该是你的datatable组件报错了。

这篇关于vue.js - 在vue中添加watch,在watch属性中添加会报错,通过实例的$watch方法添加是可以的,原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆