注册组件
// 全局注册组件
import hello from './components/HelloWorld.vue'
app.component('hello',hello)
// 在组件中引入即可使用
import hello from "../../components/HelloWorld.vue";
方法一:props传参:defineProps、defineEmits
<hello :msg="msg" @toFather="toFather"></hello>
- 子组件
// 接收参数
let props = defineProps({
title: Number,
msg: {
type: String,
default: "qq",
},
});
// 传递参数
const emit = defineEmits(["toFather", "delete"]); // 所有方法一起定义
const change = () => {
emit("toFather", 11111111);
};
const del = () => {
emit("delete", 44);
};
使用TS时
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()
// 基于类型
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
有默认值时方法1 —— withDefaults
export interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
有默认值时方法2 —— 解构
interface Props {
name: string
count?: number
}
// 对 defineProps() 的响应性解构
const { name, count = 100 } = defineProps<Props>()
方法二:provide、inject
子组件修改值,父组件会跟着一起变
// 父组件
const num = ref(1);
provide("num", num);
// 子组件
const num = inject("num");
console.log(num.value);
方法三:defineExpose 和 ref 属性
- 父组件修改值,子组件会跟着一起变
- 子组件的变量和方法暴露出去,父组件才可以通过ref 属性来调用
- 在mounted之后才可获取到子组件的变量和方法
// 子组件暴露出去
const count = ref(11);
const init = () => {
console.log(11111)
}
defineExpose({
count,
init
});
// 父组件接收
<hello ref="test"></hello>
const test = ref(); // test变量名须保持一致
onMounted(() => {
console.log(test.value.count); // 父组件获取子组件的变量
test.value.init() // 父组件调用子组件的方法
});
兄弟组件传值
$ npm install --save vue3-eventbus
import eventBus from 'vue3-eventbus'
app.use(eventBus)
- 组件1注册方法
import bus from 'vue3-eventbus'
bus.on('changeSelectedKeys',val=>{
this.selectedKeys=[]
this.selectedKeys.push(val);
})
- 组件2触发方法并传参
import bus from 'vue3-eventbus'
export default {
created() {
bus.emit('changeSelectedKeys', '2002')
}
}
props 父传子,props是只读的
- 父组件向子组件传值
- 子组件接收
自定义事件 子传父,通过defineEmits
- 父组件定义自定义事件接收参数
- 子组件定义事件,并触发传递
eventBus 全局事件总线——兄弟组件
- 因为vue3中没有 new Vue()的实例,所以需要借助mitt插件
npm i mitt --save
- 组件1定义接收事件
- 组件2去定义触发传参事件
v-model传参:实现父子组件数据同步
- v-model使用
- 同时绑定多个v-model:见vue3的pagenation组件
useAttrs——可获取组件身上的属性和方法
-父组件给子组件传递很多属性和方法
- useAttrs()获取子组件标签身上所有的属性和方法
ref 和 $parent 获取子组件、父组件实例
- ref 获取到子组件的实例,进而修改他的属性
- $parent 获取到父组件的实例,进而修改他的属性
provide 、inject 祖孙传参
pinia 集中状态管理
- 只有 state、actions、getters,没有mutations和models
- 可以定义为选项式和组合式API形式
- pinia 其中几个API
- $patch 可以批量修改 state 里面的数据
- $reset 可以重置 state 里面的数据
- $subscribe 监听 state 里面的值是否发生了变化:主要做数据持久化,存在本地
- $onAction:监听每一个action的执行,并在执行前、执行后、执行出错时执行一些特定的逻辑。
插槽
- 默认插槽
- 具名插槽
- 作用域插槽:可以传递数据的插槽