依赖注入_非空断言,css使用v-bind

provide依赖注入

// provide 和 inject 通常成对一起使用,使一个祖先组件作为其后代组件的依赖注入方,无论这个组件的层级有多深都可以注入成功,只要他们处于同一条组件链上。
// 只能在setup语法糖或者setup函数中使用,其他optionsApi只能使用配置方式
import { provide, ref, readonly } from 'vue'
const color = ref<string>('red')
provide('color', readonly(color)) 只读,防止后代组件被修改

inject

// 用于声明要通过从上层提供方匹配并注入进当前组件的属性。
import { inject, Ref } from 'vue';
const color = inject<Ref<string>>('color', [defaultValue]) // 可选默认值
const changeColor = () => {
  color!.value = 'blue' // 非空断言
}

ts_!非空断言

// 非空断言操作符操作符 ! 可以用于断言操作对象是非 null 和非 undefined 类型。即: arg! 将从 arg 值域中排除 null 和 undefined 
function handle(arg: string | null | undefined) {
  arg.split('') // null 或者undefined 会报错
  arg!.split('')
  const str:string = arg // null 或者undefined 会报错
  const str:stirng = arg! // ok
}

vue3_css使用v-bind

<style lang="less" scoped>
.box {
  background: v-bind(color)
}
</style

原文地址:http://www.cnblogs.com/JunLan/p/16852189.html

发表评论

您的电子邮箱地址不会被公开。