把博客园图标替换成自己的图标
把博客园图标替换成自己的图标end

Vue父组件和子组件之间传递数据

 

一、概念解析

挂载点: Vue实例的el属性对应的id,vue只会处理挂载点下面包含的内容
模板: 挂载点下面包含包含的标签就是模板
实例: 写上挂载点和模板等很多属性

<div id="root">
    <h1>{{msg}}</h1>
    <span></span>
</div>

 new Vue({              //new 了vue实例
        el:"#root"      //挂载点 id="root"的div,说明这个实例的范围在这个div里包含的内容
})

1、父组件向子组件传递数据
父组件通过属性向子组件传递数据
prop 是父组件用来传递数据的一个自定义属性。
父组件的数据需要通过 props 把数据传给子组件,子组件需要显式地用 props 选项声明 "prop"

<div id="app">
    <child message="hello!"></child>
</div>
 
<script>

// 子组件
Vue.component('child', {
  // 声明 props
  props: ['message'],
  template: '<span>{{ message }}</span>'
})

// 父组件
new Vue({
  el: '#app'
})
</script>

在上面的例子中定义了一个子组件child,子组件的message需要在 props属性里面显示声明,然后父组件通过message属性传了值“hello”,子组件就可以使用。

2、子组件向父组件传递数据
子组件向父组件传递数据通过监听 $emit 函数
订阅者模式:子组件触发一个函数,父组件监听这个函数。最终在父组件里定义函数处理

<div id="root">
        <div>
            <input v-model="inputValue" type="text">
            <button @click="handleSubmit">提交</button>
        </div>
        <ul>
            <todo-item
                    v-for="(item,index) of list"
                    :key="index"
                    :content="item"
                    :index="index"
                    @delete="handleDelete"      
            ></todo-item>
        </ul>
    </div>
<script>
    //子组件
    //子组件的模板是template定义的标签范围
    Vue.component('todo-item',{
        props:['content','index'],          //定义props,接收父组件传递的属性
        template:'<li @click="handleClick">{{content}}</li>',
        methods:{
            handleClick:function () {
                this.$emit('delete',this.index);   //当点击子组件的li触发delete事件
            }
        }
    })

    //父组件
    //父组件没有写template的内容,则它的模板就是挂载点容器下面包裹的所有
    new Vue({
        el:"#root",    //挂载点是id="root"的容器
        data:{
            inputValue:'',
            list:[]
        },
        methods:{
            handleSubmit:function () {
                this.list.push(this.inputValue);
                this.inputValue=''
            },
            handleDelete:function (index) {
                this.list.splice(index,1)
            }
        }
    })
</script>

···
在上面的代码里定义了,父组件、子组件。父组件通过props的方式向子组件传递数据,子组件通过触发事件的方式向父组件传递参数
下面三行代码是子组件向父组件传递参数的核心

解释说明:
@delete="handleDelete"          //父组件监听delete事件

this.$emit('delete',this.index);      //子组件发布delete事件,并且传递数据给父组件

handleDelete:function (index) {      //当父组件监听到时,拿到子组件带来的数据,进行的函数操作
                    this.list.splice(index,1)
                }

 

posted on 2019-01-07 17:57  无影尊者  阅读(768)  评论(0编辑  收藏  举报

导航

$(function(){ $(".audioplay").simplemusic({ autoplay:true, urls:["http://m1.music.126.net/gpi8Adr_-pfCuP7ZXk_F2w==/2926899953898363.mp3"] }); });