uni-app学习-------子组件的创建及父子组件互相传值(第二天)

uni-app学习-------子组件的创建及父子组件互相传值

1.子组件的创建及父组件引用子组件

子组件的创建和父组件差不多。

父组件引用子组件,先导入子组件,在<script></script>内。import name(给子组件起个名字) from "子组件地址"

然后components:{ name},然后就可以在<template></template>内使用子组件了。

2.父组件传值给子组件:

例:父组件<childs1 :text="text1" :text1="text" > </childs1>,可以传多个值,:text为键="text1"为值,可设置多个。前面的冒号是v-bind的简写

子组件:在<script></script>用props接收,因为是数据,可以解说多个。然后就可以直接用接收到的数据

3.子组件传值给父组件

例:子组件:this.emit("change2",this.value),通过this.emit(键名,键值)

父组件:<childs1 @键名="方法名" </childs1>然后在方法中获取值

方法名(res){this.value=res}

下面是例子

image

创建childs.vue

<template>
    <view >
         <view>{{text}}+{{text1}}   </view>
         <button @click="click1">点击事件</button>
    </view>
</template>
<script>
  export default {
  data(){
    return{
        value:"这是子组件的值"
    }
  },
  props:["text","text1"],
  methods:{
    click1(){
        this.$emit("change2",this.value)
    }
  } 
  }
</script>

<style>
</style>

image.gif

然后是父组件

<template>
    <view>
        <childs1 @change2="change1" :text="text1" :text1="text" > </childs1>
        <view>111 + {{value}}</view>
    </view>
</template>

<script>
    import childs1 from   "../../components/childs.vue" 
    export default {
        components:{
            childs1
        },
        data() {
            return {
                 text:"我是父组件值1",
                 text1:"我是父组件值2",
                 value:''
            }
        },
        methods: {
            change1(res){
                this.value = res
            }
        }
    }
</script>
<style>
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。