首页 文章

Vuejs未定义属性错误但已定义

提问于
浏览
1

我有一个简单的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 更改为其他内容,例如 configurationdetails ,甚至将 mounted 更改为 created ,但错误不断弹出,我的模板根本没有呈现 .

首先,我开始将 config 作为计算属性,但错误已经进入我的控制台 . 顺便说一句,使用store作为这样的计算属性也会抛出一个错误,说我的 $store 未定义:

server: () => this.$store.state.server

我能做什么?

1 回答

  • 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
    }
    

相关问题