javascript - Vuejs - 使用 Prop 将数据从 parent 传递给 child

标签 javascript vue.js

我已经开始使用 Vue,但在尝试使用 props 将数据传递到组件时遇到了问题。在下面的代码中 this.myData(在 Hello.vue 中)由于某种原因 undefined

App.vue

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

export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  } ...
 </script>

你好.vue

<script>
export default {
  name: 'hello',
  props: ['myData'],
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
  mounted: function() {
       console.log(this.myData)
   }
} ...
</script>

最佳答案

你需要在父组件中使用子组件,比如:

// inside app.vue
<template>
  <hello :myData='myData'></hello> // I believe this is your objective
</template> //:myData is binding the property from the components data field, without using it, you will get myData as `string` in the child component.

<script>
  export default {
  name: 'app',
  data() {
    return {
      myData: 'this is my data'
    }
  },
  components: {
    Hello
  }
</script>

OP 请求一种方法来将 props 传递给 child 而不在模板中渲染 child 。

所以我发布了一个指向 documentation 的链接

Vue.component('hello', {
  render: function (createElement) {
    return createElement(
      <tag-names>
    )
  },
  props: {
    myData: parentComponent.myData // you need to give the parent components' data here.
  }
})

关于javascript - Vuejs - 使用 Prop 将数据从 parent 传递给 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41668899/

相关文章:

vue.js - 查看绑定(bind):key values in Vue3

javascript - 在 Vue 中调用方法时的括号

javascript - vue-test-utils 为 document.querySelector 返回 null

javascript - 将 redis 与 socket.io 一起使用 - 如何为每个客户端更新?

javascript - 如何从对象返回值?

javascript - 如何链接 javascript 选择器

javascript - js函数表现得很奇怪

javascript - 在 redux-saga 中测试 try-catch

javascript - 在Vuejs中显示数据

无法识别 Vue.js VSCode Vetur Emmet 和 Scaffold Snippets