Vue creates global, local components and parent components to pass methods to child components

Table of contents

1. Create a global component

2. Create local components 

 3. The parent component passes the method to the child component


1. Create a global component

1. First build the scaffolding and run it to ensure the successful construction.

2. Create two vue files, the CompreHensive.vue file is used to create global variables, and OneSided.vue is used as a local variable (pay special attention to the use of camel case, otherwise it is easy to report errors).

3. Before creating global variables, configure and configure global variables in main.js. When registering components globally, the variable names must be separated by - or use camel case naming.

 4. Create the CompreHensive.vue file again, write html content in the template, write js content in the script, thank the css style in the style, and use hump naming when naming js.

5. Use in App.vue parent class.

 6. Run...

​ Global components, which can be used in multiple vue instances, are similar to global variables. 

2. Create local components 

1. Same as the first two steps of the global component, then register the component in App.vue and use it.

 

 2. All local components are registered and used in the parent class.

 

 3. Run...

 Local components can only be used in objects mounted by the current Vue instance, similar to local variables, with block-level scope. 

 3. The parent component passes the method to the child component

1. Parent class

<template>
  <div id="app">
    <my-pan :msg="msg" :arr="arr" :obj="obj" :hander="hander"></my-pan>  
          //字符串     //数组     //对象      //函数 
  </div>
</template>

<script>
import MyPan from "@/components/OneSided.vue"; 
export default {
  name: "App",
  data() {
    return {
      msg: "父组件向子组件传递方法",
      arr: [2, 4, 6, 8],
      obj: {
        name: "张三",
        age: 18,
        sex: "男",
      },
    };
  },
  components: {
    MyPan,
  },
   methods: {
    hander(){
        console.log('被点击');
    }
  },
};
</script>
<style>
</style>

2. Subclasses

<template>
  <div>
    <h2>{
   
   { msg }}</h2>
    <h2>{
   
   { arr }}</h2>
    <h2>{
   
   { obj }}</h2>
    <button @click="hand">点击</button>
  </div>
</template>
<script>
export default {
  name: "MyCpn",
  props: {
    msg: {
      type: String,  //字符串
    },
    arr: {
      type: Array,  //数组
    },
    obj: {
      type: Object,  //对象
    },
    hander: {
      type: Function,   //函数
    },
  },
  methods: {
    hand() {
      this.hander();
    },
  },

  // props:['msg'],
};
</script>
<style scoped>
h2 {
  color: red;
}
</style>

 

 

Guess you like

Origin blog.csdn.net/qq_65715980/article/details/126158639