props

props

通过 v-bind 方法进行通信

通过 :newmsg 获取 msg 的值 ---> props 定义 newmsg ---> 子组件用 newmsg 就可以获得父级的 msg 了

    <div id="app">
        <my-com :newmsg="msg"></my-com>
    </div>
const myCom = {
    template:`
            <div>
                <span>我是子组件</span>
                <div>收到父级数据:{{newmsg}}</div>
            </div>
    `,
    props:['newmsg']
}
new Vue({
    el:'#app',
    data:{
        msg:'Hello'
    },
    components: {
        myCom
    }
})
默认值
    props: {
        newmsg: {
            type: Number,
            default: "默认值",
            required: true
        }
    }

default 与 require 一般不并用

  • default: 默认值
  • require:是否需要传值

单项数据流

通过 v-bind 方法实现父级数据向子级数据传递

$emit 子级向父级反馈

    <span>父级数据{{msg}}</span>
    <my-com :name="msg" @tellme="tellme"></my-com>
    <div>~~~{{value}}</div>
const myCom = {
    template:`
        <div>
            <span>子组件</span>
            <div>收到父级数据:{{name}}</div>
            <input v-model="val">
        </div>
    `,
    props:{
        name:{
            type:Array,
            default:'name'
        }
    },
    data() {
        return{
            val:''
        }
    },
    watch:{
        val(newVal) {
            console.log(newVal);
            this.$emit('tellme',newVal)
        }
    }
}
new Vue({
    el:"#app",
    data:{
        msg:[1,2,3],
        value:''
    },
    components:{
        myCom
    },
    methods:{
        tellme(value){
            this.value = value
        }
    }
})
html&css
原文地址:https://www.cnblogs.com/goff-mi/p/9392337.html