【问题标题】:vue-router creating link but pops console errorvue-router 创建链接但弹出控制台错误
【发布时间】:2017-11-18 15:48:21
【问题描述】:

有人可以解释一下为什么我在控制台中出现错误

app.js:12666 TypeError: Cannot read property 'uuid' of undefined
    at Proxy.render (app.js:95774)
    at VueComponent.Vue._render (app.js:15384)
    at VueComponent.updateComponent (app.js:13674)
    at Watcher.get (app.js:14017)
    at new Watcher (app.js:14006)
    at mountComponent (app.js:13678)
    at VueComponent.Vue$3.$mount (app.js:19232)
    at VueComponent.Vue$3.$mount (app.js:21567)
    at init (app.js:14980)
    at createComponent (app.js:16419)

但是我在页面中获得的链接可以吗?

Vue 文件是这样的

<template>
    <div class="main-container">
        <h1 class="page-title">Protocols</h1>

        <div class="wrapper">
            <router-link :to="`/protocol/${protocolListObject.protocol.uuid}/edit`" class="dropdown-item">Click to edit</router-link>
        </div>

        </div>
</template>


<script>
    import moment from 'moment'

    export default {

        data() {
            return {
                protocolListObject: {},
                error: {},
            }
        },
        created() {
            axios.post('/getSingleProtocol/:uuid')
                .then((response) => this.protocolListObject = JSON.parse(response.data))
                .catch(error => console.log(error.response));
        },
        mounted() {

        }
    }
</script>

app.js 看起来像这样(我将删除路由和一些与此无关的内容,以使其更短)

window.Vue = require('vue');
import Vue from 'vue'
import VueRouter from 'vue-router'
import moment from 'moment'
Vue.use(VueRouter)
let ProtocolSummary = Vue.component('protocol-summary', require('./components/ProtocolSummary.vue'));
let ProtocolEdit = Vue.component('protocol-edit', require('./components/ProtocolEdit.vue'));

const routes = [
    { path: '/protocol/:uuid', component: ProtocolSummary },
    { path: '/protocol/:uuid/edit', component: ProtocolEdit },
]
const router = new VueRouter({
    mode: 'history',
    routes // short for `routes: routes`
})
Vue.prototype.moment = moment
const app = new Vue({
    router
}).$mount('#app');

但是当我加载页面时,我得到了一个带有我需要的 UUID 的链接,但是那个控制台错误看起来很糟糕,我想摆脱它

【问题讨论】:

  • 可能protocol.uuid 为空
  • 组件挂载时没有protocolListObject.protocol.uuid这样的属性,所以报错。稍后,axios请求设置属性,vue更新链接。
  • @yuriy636 是正确的,protocolListObject 的初始值是一个空数组,因为这是在 URL 内部任何方法来获取它以避免错误?
  • @yuriy636 谢谢它解决了我的问题会回答它,你把我引向正确的方向

标签: javascript vuejs2 vue-router


【解决方案1】:

像 yuriy 在上面的评论中所说的问题是,最初,我的变量是空的。从 URL 添加变量解决了问题(在 vueJS 文件中)

        data() {
            return {
                protocolListObject: {
                    protocol: {
                        uuid: this.$route.params.uuid
                    }
                },
                error: {},
            }
        },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多