vue3:父子组件传值

Vue2

父传子

父组件:

<!-- 父组件 -->
<template>
  <div>
    <children :title="title"></children>
  </div>
</template>
  
<script>
  import children from "./children.vue"
  export default {
    
    
  	components: {
    
    
  		children
  	},
    data() {
    
    
      return {
    
    
        title: "我是父组件传过来的值",
      }
    }
  }
</script>

子组件:

<!-- 子组件 -->
<template>
  <div>
    <div>父组件传过来的值: {
    
    {
    
     title }}</div>
  </div>
</template>
<script>
  export default {
    
    
    props: {
    
    
      title: {
    
    
        type: String
      }
    }
  }
</script>

子传父

父组件:

<!-- 父组件 -->
<template>
  <div>
    <children @getChildren="getChildren"></children>
  </div>
</template>
  
<script>
  import children from "./children.vue"
  export default {
    
    
    methods: {
    
    
      getChildren(val) {
    
    
        this.childrenAsk = val
      }
    }
  }
</script>

子组件:

<!-- 子组件 -->
<template>
  <div>
    <button @click="askToFather">点击发送给父组件</button>
  </div>
</template>
<script>
  export default {
    
    
    props: {
    
    
      title: {
    
    
        type: String
      }
    },
    data() {
    
    
      return {
    
    
        askMsg: "这是我给父组件说的话"
      }
    },
    methods: {
    
    
      askToFather() {
    
    
        this.$emit("getChildren", this.askMsg)
      }
    }
  }
</script>

Vue3

父传子

同 Vue2

子传父

父组件:

<template>
  <children @listen="listenToChildren"></children>
</template>

<script>
export default defineComponent({
    
    
  components: {
    
    
    children,
  },
  name: "father",
  setup() {
    
    
    let children_msg = ref("") // ref的作用是实现响应式, 如果没有ref则不能实现响应式(引用数据类型用reactive)
    let listenToChildren = (val) => {
    
    
      children_msg.value = val // 使用ref包裹的数据,需要通过.value的形式访问他的值
    }
    return {
    
    
      children_msg,
      listenToChildren,
    }
  },
})
</script>

子组件:

<template>
  <button @click="sayToFather">向父组件说话</button>
</template>

<script>
export default defineComponent({
    
    
  name: "children",
  setup(props, context) {
    
    
    // context作用是获取上下文对象,
    // 如果setup写法为setup(props, { emit })的方式的话,下面的context可以省略
    const sayToFather = () => {
    
    
      const ask = "我是子组件,我对父组件说话"
      context.emit("listen", ask)
    }
    return {
    
    
      sayToFather,
    }
  },
})
</script>

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/123229987