使用非缩小版本时未定义Vue属性或方法

问题描述 投票:1回答:2

我创建了一个简单的Vue示例,使用内联模板显示名称“John”,但却得到以下错误:

[Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

但是,如果我使用minify版本:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

该代码使用“John”字样打印出来,没有显示错误。这是某种错误还是我没有正确使用Vue?

Vue.component('profilecontent', {});

var content = new Vue({
  el: '#profile-content-wrapper',
  data: {
    name: "John",
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<!-- Minify version works
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
-->

<div id="profile-content-wrapper">
  <profilecontent inline-template>
    <div>
      <div>{{name}}</div>
    </div>
  </profilecontent>
</div>
javascript vue.js
2个回答
2
投票

并不是使用缩小版本的Vue修复了这个错误,而是当你做的事情可能不正确时,未缩小的版本会显示警告,并且缩小版本会抑制这些警告。

你使用inline-template的方式意味着Vue想要在profilecontent组件上寻找你的name变量,而不是在主app上。严格来说,你应该将name作为道具传递给那个组成部分;即使在非明确的开发模式下,这也消除了警告:

Vue.component('profilecontent', {props: ['name']});

var content = new Vue({
  el: '#profile-content-wrapper',
  data: {
    name: "John",
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<div id="profile-content-wrapper">
  <profilecontent inline-template :name="name">
    <div>
      <div>{{name}}</div>
    </div>
  </profilecontent>
</div>

(也就是说,我真的不确定为什么name变量在警告被抑制时会变成组件;内联模板中的变量范围应该是组件,而不是其父组件。)


1
投票

您应该使用<slot></slot>来组成您的组件,即:将其他元素放入其中:

Vue.component('profilecontent', {
  template: `<h1><slot></slot></h1>`
});

var content = new Vue({
  el: '#profile-content-wrapper',
  data() {
    return {
      name: "John",
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<!-- Minify version works
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
-->

<div id="profile-content-wrapper">
  <profilecontent>
    <div>
      <div>{{name}}</div>
    </div>
  </profilecontent>
</div>

如果你正在使用内联模板,你可以将name属性放在该组件的数据对象中,如:

Vue.component('profilecontent', {
   data() {
    return {
      name: "John",
    }
  }
});

var content = new Vue({
  el: '#profile-content-wrapper',
 
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

<!-- Minify version works
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
-->

<div id="profile-content-wrapper">
  <profilecontent inline-template>
    <div>
      <div>{{name}}</div>
    </div>
  </profilecontent>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.