zoukankan      html  css  js  c++  java
  • 13. VUE 组件之间数据传递

    组件数据传递:

    1. 父组件向内传递属性---动态属性
    2. 子组件向外发布事件
    3. solt 插槽传递模板---具名solt

    1. 父组件向子组件传递数据

    子组件在父组件的并作为标签引入,通过设置标签的属性传递数据,在子组件用props接受,,例如下面这样,父组件parent.vue引入子组件child.vue,将父组件的数据name通过设置标签child的name属性传递给子组件,子组件通过props传递接受,接受后,在子组件内this.name就是父组件的name数据。

    父组件:

    <template>
        <div>
            <child :name="name"></child>
        </div>
    </template>
    
    <script>
        import child from "./child"
        export default {
            name: "list",
            components: {child},
            data(){
                return {
                    name:"hello",
                }
            }
        }
    </script>
    
    <style scoped>
    
    </style>

    子组件:

    <template>
        <div>{{name}}</div>
    </template>
    
    <script>
        export default {
            name: "edit",
            props: {
                name :String
            }
        }
    </script>
    
    <style scoped>
    
    </style>

    2. 子组件向父组件传递数据

    1.发布订阅 发布 emit 订阅 on{}

    2.on订阅,emit发布,on和emit是在Vue的原型上的,每个实例都可以调用。

    3.父亲绑定一个事件,儿子触发这个事件,并将参数传递过去

    子组件:

    <template>
    <div style="margin-top: 300px;margin-left: 500px;">
    <input type="text" v-model="book"/>
    <button @click="add">添加</button>
    <p v-for="(item, index) of books" :key="index">{{item}}</p>
    </div>
    </template>

    <script>
    export default {
    name:'child',
    props:{
    books:Array
    },
    data() {
    return {
    book:""
    }
    },
    methods: {
    add(){
    this.$emit('update',this.book);
    }
    }
    }
    </script>

    <style>

    </style>

    父组件:

    <template>
    <div>
    <span>hello</span>
    <child ref="child" :books="books" @update="addBook"></child>
    </div>
    </template>

    <script>
    import child from './child';
    export default {
    components:{child},
    data: function () {
    return {
    books:[]
    }
    },
    methods: {
    addBook(data){
    this.books.push(data);
    }
     
    }
    }
    </script>

    <style>

    </style>
  • 相关阅读:
    [Jweb] JSP-编程 06, 内置对象
    [Jweb] Tomcat 解决编码, 乱码问题
    [Jweb] JSP-编程 05 JSP 使用 javabean
    [Jweb] JSP-编程 04 转向 jsp:forward 与 sendRedirect
    [Jweb] JSP-编程 03 静态, 动态包含
    [Jweb] JSP-编程 02 (Directive-include)
    [Jweb] JSP-编程 01 (Directive-page)
    [Jweb] JSP 编程 00 -Declaration- Scriptlet-表达式-Directive (推出原因 : Servlet写标签非常麻烦!)
    [Jweb] 数据库处理以及在 Servlet 中使用 Bean
    [Jweb] Application / TestServletContext.java
  • 原文地址:https://www.cnblogs.com/shix0909/p/11213733.html
Copyright © 2011-2022 走看看