wengdo网站开发创意设计,徐州网站建设一薇,免费wordpress网站模板,wordpress手机模板插件属性透传
传递给子组件时#xff0c;没有被子组件消费的属性或事件#xff0c;常见的如id、class
注意1
1.class、style是合并的#xff0c;style中如果出现重复的样式#xff0c;以透传属性为准2.id属性是以透传属性为准#xff0c;其他情况透传属性名相同#xff0c…属性透传
传递给子组件时没有被子组件消费的属性或事件常见的如id、class
注意1
1.class、style是合并的style中如果出现重复的样式以透传属性为准2.id属性是以透传属性为准其他情况透传属性名相同取值以透传属性为准
APP.vue
templatedivA stylecolor: red idfirst classapp/A/div
/templateA组件
templatediv idsecond classa stylecolor:blue; border: 1px solid gray;h2A/h2/div
/template最终html
div idfirst classa app stylecolor: red; border: 1px solid gray;h2A/h2/div注意2
1.多个根节点的时候可以为需要使用透传属性的根节点绑定v-bind“$attrs”,来确定透传属性的归属
APP.vue
templatedivA stylecolor: red idfirst classapp/A/div
/templateA组件
templatediv h2A1/h2/divdiv v-bind$attrsh2A2/h2/div
/template最终html
divdivh2A1/h2/divdiv idfirst classapp stylecolor: red;h2A2/h2/div
/div注意3
1.多层透传可以通过defineOptions({inheritAttrs:false})来实现2.透传属性使用 模板中可以直接使用$attrs.id 这种方式在js中如果在setup语法糖中可以用useAttrsjs中非
script setup
import { useAttrs } from vue;
const aa useAttrs()
console.log(aa) //aa是一个proxy对象在子组件中不能修改
/scriptAPP.vue
templatedivA stylecolor: red idfirst classapp/A/div
/templateA组件
templatediv idsecondh2A/h2B v-bind$attrs/B/div
/templatescript setup
import B from ./B.vue
import {defineOptions} from vue
defineOptions({inheritAttrs:false
})
/scriptB组件
templatedivh5B/h5p{{ $attrs.id }}/p/div
/template最终html
divdiv idsecondh2A/h2div idfirst classapp stylecolor: red;h5B/h5pfirst/p/div/div
/div注入
为了解决参数逐层传递问题
注意
1.上层组件作为提供方下层组件使用比如父组件是提供方子组件使用也可以提供全局属性2.provide 和 inject 方法需要在 setup 方法中同步调用3.修改provide属性的方式最好放在提供方统一修改4.注入时可以提供一个默认值如果没有该属性的提供方返回的为默认值5.provide的数据可以为任意类型inject后不会改变数据类型6.可以通过Symbol 来避免注入名冲突
APP.vue
templatedivA/A/div
/template
script setup
import {ref,provide} from vue
import A from ./components/A.vue
const first ref(first)
const num ref(1)
function updateFirst(val){first.value val
}
provide(first,{first,updateFirst
})
provide(num,num)
/scriptA组件
templatedivh2A/h2B/B/div
/templatescript setup
import { provide, reactive } from vue;
import B from ./B.vue
const obj reactive({name:zhangsan
})
provide(obj,obj)
/scriptB组件
templatediv styleborder: 1px solid gray;h5B/h5pfirst{{ first}}/ppbutton clickupdateFirst(inject first)change first/button/pp默认值{{ defaultTest }}/phr/pnum:{{ num }}--{{ typeof num }}/ppnum1: {{ num1 }}/p/div
/template
script setup
import { inject } from vue;
const {first,updateFirst} inject(first)
console.log(first:,first)
const defaultTest inject(defaultTest,test 默认值)
//ref 数值
const num inject(num)
//reactive
const obj inject(obj)
console.log(obj)
/script