跳到主要内容

1.4-组件值的传递

Create by fall on:2022-03-10 Recently revised in:2022-06-11

组件注册

// vue 的注册组件
Vue.component('componentName',{
data:function(){
return {count :0 }
},
template:`<button @click="handle">点击了{{count}}次</button>`,
methods:{
handle:function(){this.count +=2;}
}
})
// vue 的组件注册
var helloWorld = {
data:function(){
return{msg:0}
},
template:`<button @click="handle">点击了{{count}}次</button>`,
methods:{handle:function(){this.count +=2;}}
}
var app1 = new Vue({
el:'app1',
components:{
'hello-world'=helloWorld
}
})

  • data 必须是一个函数
    • 函数声明可以确保值的唯一性,因此组件在使用过程中,同一个组件使用多次,里面的值也是相互独立的
  • 组建模板内容必须是单个根元素
  • 组件模板内容可以是模板字符串

如果想在普通的标签模板中使用,必须采用横线方式传递组件,如果在SFC中使用,则不限制标签模板的使用。

Attributes

表示一些没有被 props(或者 defineProps) 接收的参数,将会通过 attributes 进行继承,比如说:classstyleid

举个例子:

<!-- 子组件 MyButton -->
<template>
<button>click me</button>
</template>
<!-- 父组件 -->
<template>
<MyButton class='button'>
</template>

上面的组件在运行后, 因为 并没有声明 prop 接收 class,所以 class 会由子组件的 button 继承,如果子组件已经有 class 那么就会进行合并(都生效)

事件监听同样会生效,子组件内绑定一个 v-on:click,父组件绑定一个 v-on:click,那么两个都会被触发

Provide

provide 和 inject 通常是搭配起来使用。

注册

全局注册:

import {createApp} from 'vue'
const app = createApp({})
app.provide('message','一些信息')

局部注册:

// setup 写法
import { provide,readonly } from 'vue'
/* 注入名,值 */
const msg = ref('哈哈哈')
provide('message',msg)
// 如果不希望提供的数据被修改,添加 readonly
provide('message'.readonly(msg))
<!-- 选项式 API 写法一 -->
<script>
export default{
data(){ return {message:'hello'} },
provide(){ return{ message:this.message } },
}
</script>
<!-- 选项式 API 写法二 -->
<script>
export default{
provide:{
message:'hello'
},
}
</script>

使用

选项式

export default{
inject:['message'],
data(){
return{receiveData:this.message}
}
}

组合式

import {inject} from 'vue'
const msg = inject('message')
const msg2 = inject('message','默认值') // 如果没有传递,会返回第二个参数作为默认值

推荐在供给方组件内声明并提供一个更改数据的方法函数

const {msg,updateMsg} = inject('message')

在大型项目中使用时,需要通过 Key 保证唯一性,并且通过统一的文件引入该内容,确保不会导致传递值的冲突。

组件的传递

在 React 中,所有组件,参数都可以通过 props 直接传递函数直接传递给子组件,vue 中,不能直接向子组件中传递内容,所以通过 component 组件实现

<component :is="MyButton"></component>
<script setup>
import MyButton from 'my-button'
</script>