【问题标题】:Vuejs undefined property error but it is definedVuejs未定义属性错误但已定义
【发布时间】:2017-10-23 12:08:51
【问题描述】:

我有一个简单的 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

我能做什么?

【问题讨论】:

    标签: javascript templates vue.js undefined vuex


    【解决方案1】:

    您正在为您的isHttps 计算使用箭头函数。在那种情况下,this 指的是window 而不是 Vue 实例,所以你会得到一个cannot read property of undefined 消息,正确的 ES2015 语法是:

    isHttps() { 
      return this.config.scheme === 'https'
    }
    

    server: () =&gt; this.$store.state.server 也是同样的问题,应该是:

    server() { 
      return this.$store.state.server
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2017-06-29
    • 2013-04-01
    • 2011-01-07
    相关资源
    最近更新 更多