我有一个简单的Vue组件,只列出服务器连接数据:
<template>
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h2 class="title">Data</h2>
</div>
<br>
</div>
<div class="col-xs-12">
<table class="table">
<tr>
<td>Server</td>
<td><strong>{{config.servers}}</strong></td>
</tr>
<tr>
<td>Port</td>
<td><strong>{{config.port}}</strong></td>
</tr>
<tr>
<td>Description</td>
<td><strong>{{config.description}}</strong></td>
</tr>
<tr>
<td>Protocol</td>
<td :class="{'text-success': isHttps}">
<i v-if="isHttps" class="fa fa-lock"></i>
<strong>{{config.scheme}}</strong>
</td>
</tr>
</table>
</div>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'Application',
data () {
return {
config: {
scheme: '',
servers: '',
port: '',
description: ''
}
}
},
computed: {
...mapState(['server']),
isHttps: () => this.config.scheme === 'https'
},
mounted () {
const matched = this.server.match(/(https?):\/\/(.+):(\d+)/)
this.config = {
scheme: matched[1],
servers: matched[2],
port: matched[3],
description: window.location.hostname.split('.')[0] || 'Server'
}
}
}
</script>
安装此组件时已定义并完成Vuex中的server
,如果我尝试console.log(this.server)
,则会显示正确的URL。问题是,我的计算属性isHttps
抛出以下错误:
[Vue warn]: Error in render function: "TypeError: Cannot read property 'scheme' of undefined"
found in
---> <Application> at src/pages/Aplicativo.vue
<App> at src/App.vue
<Root>
我已尝试将config
更改为其他内容,例如configuration
或details
,甚至将mounted
更改为created
,但错误不断弹出,我的模板根本没有呈现。
首先,我开始将config
作为计算属性,但错误已经进入我的控制台。顺便说一下,使用store作为这样的计算属性也会抛出一个错误,说我的$store
未定义:
server: () => this.$store.state.server
我该怎么办?
答案 0 :(得分:0)
您正在为isHttps
计算使用箭头功能。在该上下文中,this
引用window
而非Vue实例,因此您将收到cannot read property of undefined
消息,正确的ES2015语法为:
isHttps() {
return this.config.scheme === 'https'
}
server: () => this.$store.state.server
也应该是同样的问题:
server() {
return this.$store.state.server
}