Vue 开发必须知道的36个技巧(小结)

2020-06-12 21:07:05易采站长站整理

2.类似于 Vuex。但这种方式只适用于极小的项目
3.原理就是利用$on和$emit 并实例化一个全局 vue 实现数据共享


// 在 main.js
Vue.prototype.$eventBus=new Vue()

// 传值组件
this.$eventBus.$emit('eventTarget','这是eventTarget传过来的值')

// 接收组件
this.$eventBus.$on("eventTarget",v=>{
console.log('eventTarget',v);//这是eventTarget传过来的值
})

4.可以实现平级,嵌套组件传值,但是对应的事件名eventTarget必须是全局唯一的

3.12 broadcast和dispatch

vue 1.x 有这两个方法,事件广播和派发,但是 vue 2.x 删除了

下面是对两个方法进行的封装


function broadcast(componentName, eventName, params) {
this.$children.forEach(child => {
var name = child.$options.componentName;

if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
broadcast.apply(child, [componentName, eventName].concat(params));
}
});
}
export default {
methods: {
dispatch(componentName, eventName, params) {
var parent = this.$parent;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;

if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
},
broadcast(componentName, eventName, params) {
broadcast.call(this, componentName, eventName, params);
}
}
}

3.13 路由传参

1.方案一


// 路由定义
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
// 页面传参
this.$router.push({
path: `/describe/${id}`,
})
// 页面获取
this.$route.params.id

2.方案二


// 路由定义
{
path: '/describe',
name: 'Describe',
omponent: Describe
}
// 页面传参
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
// 页面获取
this.$route.params.id

3.方案三


// 路由定义
{
path: '/describe',
name: 'Describe',
component: Describe
}
// 页面传参
this.$router.push({
path: '/describe',
query: {
id: id
`}
)
// 页面获取
this.$route.query.id

4.三种方案对比
方案二后面参数页面刷新会丢失
方案一参数拼接在后面,丑,而且暴露了信息
方案三不会在后面拼接参数,刷新参数也不会丢失