VUE3.0学习系列随笔(五):自定义组件使用

VUE3.0学习系列随笔(五):自定义组件使用

VUE2.0和VUE3.0虽然在工程目录结构上存在较大差异,但是具体的代码实现逻辑相同,本文所使用的自定义组件方法,同样适用于VUE2.0。

1、无参子组件的自定义和调用
(1)定义无参子组件

自定义组件已办存放在VUE工程结构的component文件夹下,新建自定义组件的方式和新建普通vue文件一样,整个VUE代码结构,本文自定义head组件,主要是作为页面的顶部div使用,代码如下:

<template>
  <div class="head">
    <span>我是子组件span>
  div>
template>

<script>
export default {
  name: 'Head'
}
script>

<style scoped>
.head{
  width: 100%;
  height: 100px;
  background-color: aqua;
}
style>
(2)调用无参子组件

自定义组件的调用有两种方式:全局调用和局部调用。
全局调用适用于整个项目工程,局部调用只适用于当前vue文件

a、全局调用

全局引用自定义组件需要在main.js中进行申明和引用
VUE3.0,在main.js中引用代码为:

import { createApp } from 'vue'
import App from './App.vue'
import Head from '@/components/head.vue'

const Vue = createApp(App)

Vue.component('Head', Head)
Vue.mount('#app')

VUE2.0,在main.js中引用代码为:

import Vue from 'vue'
import App from './App.vue'
import Head from '@/components/head.vue'

Vue.component('Head', Head)

new Vue({
	render: h => h(App)
}).$mount('#app)

父组件在使用全局调用子组件时,需要注意子组件标签要和子组件参数中的name值一致,否则会调用失败,代码:

<template>
  <div class="home">
    
    <Head>Head>
    <span>我是主要部分span>
  div>
template>

<script>
export default {
  name: 'Home'
}
script>

<style scoped>
.home{
  width: 100%;
  height: 500px;
  background-color: antiquewhite;
}
style>
b、局部调用

局部调用需要先引入组件代码import Head from '@/components/head.vue',然后在父组件中进行申明,代码为:

<template>
  <div class="home">
    
    <Head>Head>
    <span>我是主要部分span>
  div>
template>

<script>
// 局部引入自定义组件
import Head from '@/components/head.vue'

export default {
  name: 'Home',
  // 局部引入自定义组件
  components: {
    Head
  }
}
script>

<style scoped>
.home{
  width: 100%;
  height: 500px;
  background-color: antiquewhite;
}
style>

子组件调用效果为:
VUE3.0学习系列随笔(五):自定义组件使用_第1张图片

2、有变量的子组件定义和调用
(1)定义有变量的子组件

有参子组件的定义和普通带普通变量的VUE文件定义一样

<template>
  <div class="head">
    <span>{{msg}}span>
  div>
template>

<script>
export default {
  name: 'Head',
  data () {
    return {
      msg: '我是头部'
    }
  }
}
script>

<style scoped>
.head{
  width: 100%;
  height: 200px;
  background-color: aqua;
}
style>
(2)有变量的子组件的调用

在调用有变量的子组件的时,需要在子组件标签中定义指向ref,即,引用变量的方式为this.$refs.Head.msg,同时也可以进行修改,以局部调用组件为例:

<template>
  <div class="home">
    <Head ref='Head'>Head>
    <span>我是主要部分span>
  div>
template>

<script>
import Head from '@/components/head.vue'

export default {
  name: 'Home',
  components: {
    Head
  },
  mounted () {
    alert(this.$refs.Head.msg)
    this.$refs.Head.msg = '正在调用子组件'
  }
}
script>

<style scoped>
.home{
  width: 100%;
  height: 500px;
  background-color: antiquewhite;
}
style>

调用子组件的效果为:
VUE3.0学习系列随笔(五):自定义组件使用_第2张图片

你可能感兴趣的:(VUE3.0学习随笔,VUE2.0学习随笔,vue,html,html5)