Vuejs - 使用道具将数据从父级传递给子级 [英] Vuejs - pass data from parent to child with props
本文介绍了Vuejs - 使用道具将数据从父级传递给子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经开始使用 Vue
,但在尝试使用 props
将数据传递给组件时遇到了问题.在下面的代码中 this.myData
(在 Hello.vue
中)由于某种原因是 undefined
I have started playing with Vue
but faced an issue when trying to pass data to a component using props
. In the code below this.myData
(in the Hello.vue
) is undefined
for some reason
App.vue
<script>
import Hello from './components/Hello'
export default {
name: 'app',
data() {
return {
myData: 'this is my data'
}
},
components: {
Hello
} ...
</script>
Hello.vue
<script>
export default {
name: 'hello',
props: ['myData'],
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
mounted: function() {
console.log(this.myData)
}
} ...
</script>
推荐答案
需要在父类中使用子组件,所以:
You need to use the child component in the parent like, so:
// 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 传递给子级而不在模板中渲染子级的方法.
OP requested a way to pass in props to a child without rendering the child in the template.
所以我发布了一个链接到文档
So I am posting a link to the documentation
Vue.component('hello', {
render: function (createElement) {
return createElement(
<tag-names>
)
},
props: {
myData: parentComponent.myData // you need to give the parent components' data here.
}
})
这篇关于Vuejs - 使用道具将数据从父级传递给子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文