Vue - 将 v-for 中具有相同键名的父数据传递给子组件 [英] Vue - Passing parent data with same key name in v-for to child component
问题描述
父组件:
<模板><div id="用户">你好呀!{{msg}} {{name}}您有以下消息<Message v-for='(msg,index) in messages':messageText='msg':messageNumber='索引+1':welcome-msg='{{msg}}'></Message>
</模板><脚本>从./Message.vue"导入消息;导出默认{数据 () {返回 {msg: '欢迎亲爱的',name: 'Max',消息:['消息1','消息2']}},成分: {信息}}
子组件:
<模板><div>{{messageNumber}}.{{messageText}} - {{welcomeMsg}}
</模板><脚本>导出默认{道具: {messageNumber:号码,消息文本:字符串,欢迎消息:字符串}}
我正在尝试将数据 msg('Welcome Dear')从父母传递给孩子.有没有办法指定访问welcome-msg prop的父msg?
注意:我知道我可以通过更改 v-for 来使其工作.我刚刚开始学习 Vue.js,很想知道是否有办法通过某种范围界定来访问父级的数据
更新:这不是变量阴影的重复,因为对于变量阴影,有一种方法可以使用 window.functionName 调用全局函数.这个问题特定于 Vue.js &因此我不相信这是重复的.
想知道是否有办法通过某种范围界定访问父级的数据
这不可能.您需要选择不同的变量名称来区分它们.
您可以做这样的事情,但这不是比选择不同的名称更好的解决方案:
//在代码的开头某处...Object.defineProperty(Vue.prototype, '$self', {get() { 返回这个 }})
{{消息}}</消息>
Parent Component:
<template>
<div id="user">
Hello there! {{msg}} {{name}}
You have below messages
<Message v-for='(msg,index) in messages'
:messageText='msg'
:messageNumber='index+1'
:welcome-msg='{{msg}}'></Message>
</div>
</template>
<script>
import Message from "./Message.vue";
export default {
data () {
return {
msg: 'Welcome dear',
name: 'Max',
messages: [ 'Message 1', 'Message 2']
}
},
components: {
Message
}
}
</script>
Child Component:
<template>
<div>
{{messageNumber}}. {{messageText}} - {{welcomeMsg}}
</div>
</template>
<script>
export default {
props: {
messageNumber: Number,
messageText: String,
welcomeMsg: String
}
}
</script>
I am trying to pass the data msg ('Welcome dear') from parent to the child. Is there a way to specify to access the parent msg for welcome-msg prop ?
Note: I am aware that I can make it work by changing the v-for like. I have just started learning Vue.js and curious to know if there is a way to access parent's data through some sort of scoping
<Message v-for='(item,index) in messages'
:messageText='item'
:messageNumber='index+1'
:welcome-msg='msg'></Message>
Update: This is not a duplicate of variable shadowing, as with variable shadowing there is a way to invoke the global function using window.functionName. This question is specific to Vue.js & hence I am not convinced this is a duplicate.
curious to know if there is a way to access parent's data through some sort of scoping
This isn't possible. You need to choose a different variable name to distinguish between them.
You could do something like this, but it's not a better solution than just choosing a different name:
// At the beginning of your code somewhere...
Object.defineProperty(Vue.prototype, '$self', {
get() { return this }
})
<Message v-for="msg in messages" :messageText="$self.msg">
{{ msg }}
</Message>
这篇关于Vue - 将 v-for 中具有相同键名的父数据传递给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!