美文网首页
vue 组件传递参数

vue 组件传递参数

作者: 云龙789 | 来源:发表于2019-01-26 15:17 被阅读0次

    对应VUE手册章节

    第一种方式 也是常用的方式

    <div id="app">
        <blog-post
                v-for="post in posts"
                v-bind:post="post"
                v-bind:key="post.id"
                v-bind:title="post.title"
        ></blog-post>
    </div>
    
    <script>
        Vue.component('blog-post', {
            props: ['post'], // 也可以使用title 模板中直接传递 title 
            template: '<h3>{{ post.title }}</h3>'
        })
        var vm = new Vue({
                el: '#app',
                data: {
                    posts: [
                        {id: 1, title: 'My journey with Vue'},
                        {id: 2, title: 'Blogging with Vue'},
                        {id: 3, title: 'Why Vue is so fun'}
                    ]
                },
            })
        ;
    </script>
    
    • 总结
      传递参数的语法就是 v-bind:属性="vm.data 中的值",也就是
      1、将 vue 中 data 的值,通过 v-bind: 之后的属性传递给组件,
      2、组件如果需要使用,需要在组件的 props 中声明这个属性,才能在组件的模板中使用这个属性

    第二种方式

    <div id="app">
        <blog-post title="My journey with Vue"></blog-post>
        <blog-post title="Blogging with Vue"></blog-post>
        <blog-post title="Why Vue is so fun"></blog-post>
    </div>
    
    <script>
        Vue.component('blog-post', {
            props: ['title'],
            template: '<h3>{{ title }}</h3>'
        })
        var vm = new Vue({
            el:'#app'
        });
    </script>
    
    • 总结
      这种方式 组件中的数据不是来自于 vue 的 data,而是来自于自己的组件,
      因为 v-bind:属性 的这种语法是适用于 vue.data 传递数据,此处没有传递,
      1、所有可以直接在属性上赋值,
      2、赋值后,如果模板想使用这个值,还是需要使用 props 接收这个参数的传递,这是语法规则

    相关文章

      网友评论

          本文标题:vue 组件传递参数

          本文链接:https://www.haomeiwen.com/subject/ixyijqtx.html