关于Prop传值问题。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Component</title>
</head>
<body>
    <div id="app">

    <hello-world message="Hello Vue"></hello-world>

    </div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>

Vue.component('hello-world',{
  template: '<h1>Hello World and {{ message }}</h1>',
  props: ['message']
})

var app = new Vue({
  el: '#app',
  data: {
      
  }
})

</script>    
</body>
</html>

props 是父组件给子组件传值用的。
在这里的父组件是什么呢?
是,<hello-world message="Hello Vue"></hello-world>吗?

但<hello-world>这个组件在子组件定义的。。。

哪位大神给讲下。谢谢~

阅读 1.9k
2 个回答

hello-world是子组件,父组件是hello-world所在的上下文,也就是这个文件所处的环境。

根,一般都是命名App,渲染结构是组件套组件,所以,父组件、子组件定义。

image.png

你这里message="Hello Vue"传的是文本字符串,如果是变量的话,就需要在hello-world所在的上下文(也就是问题中的文件)中定义。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Component</title>
</head>
<body>
    <div id="app">
        <hello-world :message="message"></hello-world>
    </div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>


var app = new Vue({
  el: '#app',
  data: {
    message: '我是父组件的消息,马上传递给子组件'
  },
    components:{     
        'hello-world':{
            template:'<h1>Hello {{ message }}</h1>',
            props: ['message'],
            data: function () {
                return {
                    childData: 0
                }
            }
        }
    }  
})

</script>    
</body>
</html>

http://jsrun.pro/g3fKp

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题