vue最常见的,容易为难新手的,应该就是组件间的传参的,所以本次笔记就记录下传参,顺带也记录下vue2吧
父组件atherTitle,fatherMoney,fatherWifi,thisIsEmpty等都是传过去给子组件的
props.vue传递父组件的参数到子组件,子组件用defineProps接收,fatherTitle和fatherMoney参数
子组件接收defineProps() 接收父组件传递过来的参数,defineProps在setup语法糖可以直接使用,不需要import
son.vue:{{sonTitle}}-------{{fatherTitle}}-----{{fatherMoney}}
{{fatherWifi}}--{{fatherWifi.pwd}}--{{fatherWifi.name}}
父传递的空字符串:{{myEmptyStr}}
{{item}},{{item.code}}
TS 特有的默认值方式
withDefaults是个函数也是无须引入开箱即用接受一个props函数第二个参数是一个对象设置默认值
type Props = {
title?: string,
data?: number[]
}
withDefaults(defineProps(), {
title: "张三",
data: () => [1, 2, 3]
})
子组件
父组件@onMySonFunc=“funcToSon”,这样上面的子组件就能调用到父组件的funcToSon()方法了
父组件provide传递参数到其他子孙组件
儿子组件用inject接收父组件传递过来的参数
孙子组件也可以用inject接收父组件传递过来的参数
mitt || tiny-emitter
)mitt 使用举例:
// eventBus.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;
// a.js
import emitter from './utils/eventBus'
emitter.emit('panda', {name: 'lokka', age: 2})
emitter.emit('flamingo', {name: 'disy', age: 1})
// b.js
import emitter from './utils/eventBus'
// 逐个监听
—————————————————————————————————————————
emitter.on('panda', (val) => {
console.log(val)
})
emitter.on('flamingo', (val) => {
console.log(val)
})
// 取消监听
funtion onFoo() {}
emitter.on('foo', onFoo)
emitter.off('foo', onFoo)
—————————————————————————————————————————
// 监听多个
emitter.on('*', (type, val) => {
console.log(type, val)
})
// 取消监听多个
emitter.all.clear()
父组件:
子组件:
父组件
我是Father组件
子组件
我是Son组件
父组件
我是Father组件
子组件
我是Son组件
父组件
// 父组件把方法传入子组件中,在子组件里直接调用这个方法
子组件
父组件
我是Father组件
子组件
我是Son组件
$root
和 $parent
都能够实现访问父组件的属性和方法,两者的区别在于,如果存在多级子组件,通过parent 访问得到的是它最近一级的父组件,通过root 访问得到的是根父组件(App.vue) 所以存在组件嵌套的情况下 不要使用 $root
父组件
// ref 作用在组件上 指向的是组件的实例 实例上的方法都可以调用
子组件
在main.js种挂载全局EventBus
Vue.prototype.$EventBus = new Vue()
A组件
我是组件A
B组件
我是组件B
provide
/ inject
)provide是父级组件需要传递给子孙组件的属性/方法
//选项一
provide: {
content: 'hello world'
}
//选项二
provide(){
return {
content: 'hello world'
}
}
inject是子孙组件用来接收父级组件属性/方法
//选项一
inject: ['content']
//选项二
inject: {
content: 'content'
}
//选项三
inject: {
content: {
from:'content',
default:'hello world'
}
}
a.vue
{{a}}
aa.vue
$attrs
/ $listeners
)父组件
{{name}}
{{price}}
子组件aa.vue
{{name}}
子组件aaa.vue
总结: $attrs 与 l i s t e n e r s 是两个对象, listeners 是两个对象, listeners是两个对象,attrs 里存放的是父组件中绑定的非 Props 属性,$listeners里存放的是父组件中绑定的非原生事件。
安装 pubsub-js
插件: npm i pubsub-js -s
可实现全局参数传递
publishSync
同步发送消息publish
同步发送消息subscribe
订阅消息unsubscribe
卸载特定订阅clearAllSubscriptions
清除所有订阅组件A
我是组件A
组件B
我是组件B
查看附件
methods: {
society() {
//console.log('society');
this.$router.push({
name:'society',
query:{value:1}
})
},
methods:{
loadData:function(){
this.id = this.$route.query.order_id;
axios.get("http://testqywx.origimed.com:18082/weixin-qy/order/Order/userOrderFilesList.json?usercode=sysadmin&orderId="+this.id)
.then(response=>this.tasks=response.data.reason);
}
},
哎呀,累了,没想到总结下来,还不少,暂时先这么多吧,回头有了再更新~