Vue不显示传递给子Vue的参数

时间:2019-12-01 20:12:01

标签: vue.js

嗨,我有2个简单的提示,我想将属性从父级传递到子级,但是我的显示为空(只有徽标,没有名字,姓氏和param)

父App.vue:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Hello firstname='John' lastname='Doe' from='New York' img='/src/assets/logo.png'/>
  </div>
</template>

<script>
import Hello from './components/Hello.vue'

export default {
  name: 'app',
  components: {
    Hello
  }
}
</script>

和hello.vu:

<template>
  <div>
    <img :src="img">
    <h1> Hello {{ firstname }} {{ lastname }} de {{ from }}</h1>
  </div>
</template>

<script>
export default {
  data () {

  },
  props: ['firstname', 'lastname', 'from']
}
</script>

我检查了两次语法,对我来说似乎还不错,不知道为什么它只显示非文本

2 个答案:

答案 0 :(得分:1)

您需要绑定数据,而不仅仅是将其作为属性传递。因此:

<Hello firstname='John' lastname='Doe' from='New York' img='/src/assets/logo.png'/>

应该是这样:

<Hello :firstname="'John'" :lastname="'Doe'" :from="'New York'" :img="'/src/assets/logo.png'"/>

以冒号:为前缀,使该属性成为prop。双引号内的所有内容都被评估为JavaScript,因此必须将单引号中的字符串传递,才能将其识别为字符串而不是变量。

理想情况下,您应该这样做:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Hello :firstname="firstName" :lastname="lastName" :from="location" :img="image"/>
  </div>
</template>

<script>
import Hello from './components/Hello.vue'
import logo from './assets/logo.png'

export default {
  name: 'app',
  components: {
    Hello
  },
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe',
      location: 'New York',
      image: logo
    }
  }
}
</script>

需要注意的是,绑定值周围不再有单引号,这是因为它们不再是字符串,而是来自包含字符串的数据对象的变量。始终将您的内容与代码的逻辑分开。您会发现维护代码容易得多。我们现在还导入图像资产,并将其作为变量通过数据对象传递给组件。

答案 1 :(得分:0)

在将字符串作为道具发送时,不需要绑定值。

解决方案:只需将单个'更改为两个"

-  <Hello firstname='John' lastname='Doe' from='New York' img='/src/assets/logo.png'/>
+  <Hello firstname="John" lastname="Doe" from="New York" img="/src/assets/logo.png"/>

附加说明:

Vue的工作方式如下:

<some-component userName="John" name="title" />

如果在SomeComponent中指定道具userNamename

{
  ...,
  props: ['userName', 'name'],
  ...,
}

数据将被视为道具。在这种情况下,字符串“ John”和字符串“ title”。 Vue足够聪明;-)

但是,如果不这样做,Vue会将userNamename作为属性添加到$attrs对象。