axdbk  

1.父组件向子组件传值

父组件传值

<template>
  <div>
    <children :transmit="account"></children>
  </div>
</template>
<script>
import children from './children.vue'
export default {
  data() {
    return {
      account: 'admin',
    }
  },
  components: {
    children
  }
}
</script>

子组件通过props接收

<template>
  <div>
    {{transmit}}
  </div>
</template>
<script>
export default {
  name: 'children',
  props: ['transmit'],
  // props: {
  // transmit: {
    // type: String,
    // default: null
  // }
  },
}
</script>

 

2.子组件向父组件传值

父组件接收

<template>
  <div>
    <children @childFn="parentFn"></children>
  </div>
</template>
<script>
import children from './children.vue'
export default {
  data() {
    return {
      message: '',
    }
  },
  components: {
    children
  },
  methods: {
    parentFn(childData) {
      console.log(childData)
      this.message = childData;
    }
  }
}
</script>
子组件通过$emit向父组件传值

<template>
  <div>
    <input type="text" v-model="message" />
    <button @click="sendClick">发送给父组件</button>
  </div>
</template>
<script>
export default {
  name: 'children',
  data() {
    return {
      message: '',
    }
  },
  methods: {
    // 发送
    sendClick() {
      this.$emit('childFn', this.message);
    }
  }
}
</script>
3.父组件调用子组件里的方法

父组件

<template>
  <div @click="fatherMethod">
    <child ref="child"></child>
  </div>
</template>
<script>
import child from '~/components/dam/child.vue';
export default {
  components: {
    child
  },
  methods: {
    fatherMethod() {

      this.$refs.child.childMethods();
    }
  }
};
</script>
子组件

<template>
  <div>{{name}}</div>
  </template>
<script>
export default {
  data() {
    return {
      name: '测试'
    };
  },
  methods: {
    childMethods() {
      console.log(this.name);
    }
  }
};
</script>

4.子组件调用父组件里的方法

父组件

<template>
  <div>
    <child></child>
  </div>
</template>
<script>
import child from './components/childcomponent';
export default {
  components: {
    child
  },
  methods: {
    fatherMethod() {
      console.log('父组件方法');
    }
  }
};
</script>
子组件

<template>
  <div>
    <button @click="childMethod()">点击按钮</button>
  </div>
</template>
<script>
export default {
  methods: {
    childMethod() {
      this.$parent.fatherMethod();
    }
  }
};
</script>

 

posted on 2022-06-20 10:37  前端真难123  阅读(38)  评论(0编辑  收藏  举报