vue 组件传值,(太久不用就会忘记,留在博客里,方便自己查看)

一 :父组件 传值给 子组件

方法: props

//父组件
<template lang="html">
    <div>
        <h3>我是父亲</h3>
        <Children :patText="partentText"/>
    </div>
</template>

<script>
import Children from "./children"
export default {
    data () {
        return {
            partentText: "我是要给儿子的值"
        }
    },
    components: {
        Children
    },
    computed: {
    },
    methods:{
    }
}
</script>

//子组件
<template lang="html">
    <div>
        <h3>小儿子</h3>
        <p>展示父组件传递的值 {{ patText }}</p>
    </div>
</template>

<script>
export default {
    name: 'Children',
    data () {
        return {
        }
    },
    props:{
        patText:{
            type: String,//类型为字符窜
            default: "123"//默认类型
        }
    }
}

一 :子组建 传值给 父组建  

方法: $emit 

//父组件
1
<template lang="html"> 2 <div> 3 <h3>我是父亲</h3> 4 <Children @keyk="watchChild"/> 5 </div> 6 </template> 7 8 <script> 9 import Children from "./children" 10 export default { 11 data () { 12 return { 13 } 14 }, 15 components: { 16 Children 17 }, 18 computed: { 19 }, 20 methods:{ 21 watchChild(data) { 22 console.log(data); 23 } 24 } 25 } 26 </script>

//子组件
<template lang="html"> <div> <h3>小儿子</h3> <button @click="target">点击触发</button> </div> </template> <script> export default { name: 'Children', data () { return { childText: "我将要给到父亲去" } }, props:{ patText:{ type: String,//类型为字符窜 default: "123"//默认类型 } }, methods:{ target() { this.$emit('keyk',this.childText) } } } </script>

路由传值:

方法: $route.parms

注意是$route 不是 $router 

//路由
<router-link :to="{ name: '', params: {newsHeader: '消息'} }"></router-link>

//组件中获取
this.$route.parms.newsHeader
原文地址:https://www.cnblogs.com/ralapgao/p/9479520.html